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
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 grep
ping here. Not only is grep
ping ls
unnecessary (use a glob
instead), this particular case is grep
ping 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:
ls
: http://mywiki.wooledge.org/ParsingLs glob
s: http://mywiki.wooledge.org/glob If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With