Don't use grep --color=always
, that's precisely why GNU grep
(and maybe others) also have grep --color=auto
which is equivalent to grep --color
alone (from man grep
):
--color[=WHEN], --colour[=WHEN]
Surround the matched (non-empty) strings, matching lines,
context lines, file names, line numbers, byte offsets, and
separators (for fields and groups of context lines) with escape
sequences to display them in color on the terminal. The colors
are defined by the environment variable GREP_COLORS. The
deprecated environment variable GREP_COLOR is still supported,
but its setting does not have priority. WHEN is never, always,
or auto.
I can't find where this is documented in more detail but it basically detects whether the output of grep
is a file or a terminal or a pipe or whatever and acts accordingly:
$ echo foo | grep --color=always o | grep m
f[01;31mo[m[01;31mo[m
$ echo foo | grep --color=always o >outfile; grep m outfile
f[01;31mo[m[01;31mo[m
Compare the above to
$ echo foo | grep --color o >outfile; grep m outfile
$ echo foo | grep --color o | grep m
$
So, using the auto
option will basically only print the colors when you can see them. It is really very clever and works like a charm. So much so, that I have:
$ type grep
grep is aliased to `grep --color'
--color=always
?egrep
and concatenate the patterns with "|".egrep
does not help me here.