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:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…