Your grep is probably removing ls
' 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
output very stupid (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. You should never pipe ls
into anything, and never capture its output. ls
is ONLY ever 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: