Preserve colouring after piping grep to grep

2019-03-08 01:25发布

问题:

There is a simlar question in Preserve ls colouring after grep’ing but it annoys me that if you pipe colored grep output into another grep that the coloring is not preserved.

As an example grep --color WORD * | grep -v AVOID does not keep the color of the first output. But for me ls | grep FILE do keep the color, why the difference ?

回答1:

grep sometimes disables the color output, for example when writing to a pipe. You can override this behavior with grep --color=always

The correct command line would be

grep --color=always WORD * | grep -v AVOID

This is pretty verbose, alternatively you can just add the line

alias cgrep="grep --color=always"

to your .bashrc for example and use cgrep as the colored grep. When redefining grep you might run into trouble with scripts which rely on specific output of grep and don't like ascii escape code.



回答2:

A word of advice:

When using grep --color=always, the actual strings being passed on to the next pipe will be changed. This can lead to the following situation:

$ grep --color=always -e '1' * | grep -ve '12'
11
12
13

Even though the option -ve '12' should exclude the middle line, it will not because there are color characters between 1 and 2.



回答3:

although a bit 'hack-ish', it also works to simply repeat the grep command at the end of your pipe.
grep WORD * | grep -v AVOID | grep WORD