Preserve ls colouring after grep'ing

duckyflip picture duckyflip · May 15, 2009 · Viewed 10k times · Source

If I do

$ ls -l --color=always

I get a list of files inside the directory with some nice colouring for different file types etc..

Now, I want to be able to pipe the coloured output of ls through grep to filter out some files I don't need. The key is that I still want to preserve the colouring after the grep filter.

$ ls -l --color=always | grep -E some_regex

^ I lose the colouring after grep

EDIT: I'm using headless-server Ubuntu 8.10, Bash 3.2.39, pretty much a stock install with no fancy configs

Answer

lhunath picture lhunath · May 15, 2009

Your grep is probably removing ls's color codes because it has its own coloring turned on.

You "could" do this:

ls -l --color=always | grep --color=never pattern

However, it is very important that you understand what exactly you're grepping here. Not only is grepping ls unnecessary (use a glob instead), this particular case is grepping through not only filenames and file stats, but also through the color codes added by ls!

The real answer to your question is: Don't grep it. There is never a need to pipe ls into anything or capture its output. ls is only intended for human interpretation (eg. to look at in an interactive shell only, and for this purpose it is extremely handy, of course). As mentioned before, you can filter what files ls enumerates by using globs:

ls -l *.txt      # Show all files with filenames ending with `.txt'.
ls -l !(foo).txt # Show all files with filenames that end on `.txt' but aren't `foo.txt'. (This requires `shopt -s extglob` to be on, you can put it in ~/.bashrc)

I highly recommend you read these two excellent documents on the matter: