Use --color=always
.
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:
foo ^[[01;31m^[[Kbar^[[m^[[K
from e.g.:
grep pattern file > result
To override use --color=always
.
grep --color=always pattern file | ...
Example:
Having file:
ID=111;Year=2013;foo=bar
ID=222;Year=2013;foo=baz
Then
grep --color=always ID file | grep --color=always 2013 | grep foo
would color ID
, 2013
and foo
.
grep --color=always ID file | grep 2013 | grep foo
would color ID
and foo
, but not 2013
.
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. ID=111
.
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:
export GREP_OPTIONS="--color=always"
to your .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.
Add an alias
if you use it often.
alias cgrep='grep --color=always'
GREP_OPTIONS
and --color
take three options: never
, auto
and always
. The two first should be the only ones considered for GREP_OPTIONS
.
You could also check out GREP_COLORS
in the man
pages or at gnu grep.
grep -E '^([^#].*)?app' ./infiles* /dev/null
I guess the comments already nearly had it anyway, but if you make the head of line [^#]
not-comment match ?
optional, then you either get lines that begin with the match app or you get lines which begin with something else and then eventually match app - but either way, you don't get lines that begin with #
.
Regarding the colors - well... that depends on the grep
and the regexp, but a standard GNU grep should highlight the whole match up to the last app match. If you would like it more specific you can do info grep
to have a look at what environment vars a GNU grep
will consider when highlighting and configure them appropriately , or, failing a satisfactory result in that vein, highlight it yourself.
Best Answer
For what it's worth, this is exactly the reason why
--color
defaults to--color=auto
and not--color=always
.If your goal is "Show me all lines that contain both
A
andm
and highlight the matchingA
andm
characters", it seems like the simplest solution would be to do all the highlighting after all of the matching, using one egrep to add the highlighting back in. Something like: