Question

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

Was it helpful?

Solution

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:

OTHER TIPS

You should check if you are really using the "real" ls, just by directly calling the binary:

/bin/ls ....

Because: The code you described really should work, unless ls ignores --color=always for some weird reason or bug.

I suspect some alias or function that adds (directly or through a variable) some options. Double-check that this isn't the case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top