If I use two consecutive
grep commands, e.g.:
echo "foo bar" | grep foo | grep bar
Then the first pattern ("foo") is not highlighted. In fact, it seems that grep removes color codes from its input. Is there any way to prevent this?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
grep detects if output is to a pipe (or file). You most never want colors when output is to file – as that is escape sequences for the terminal. Typically:
grep pattern file > result
To override use
grep --color=always pattern file | ...
grep --color=always ID file | grep --color=always 2013 | grep foo
grep --color=always ID file | grep 2013 | grep foo
foo, but not
1Important: You also have to remember that the added clutter from colors is passed
to next command in the chain. Once ID is colored, you can't (with ease), match e.g.
On some occasion one would perhaps want terminal colors in file. Try e.g.
grep --color=always foo file > result cat result
Though the resulting file would have very limited portability.
The coloring itself is also an extension.
As mentioned by the good @slm, you could add:
.bashrc etc, but don't unless you for some reason really understand the implications and still want to do it. It would in many ways break
grep due to the fact mentioned above 1.
alias if you use it often.
alias cgrep='grep --color=always'
--color take three options:
always. The two first should be the only ones considered for
You could also check out
GREP_COLORS in the
man pages or at gnu grep.