Grep output with multiple Colors?
If you want something out of the box, you're probably looking for hhighlighter.
Here's an example:
Take a look. It's incredibly useful for coloring words in different colors automatically. It's an impressive project that's built on top of ack.
grep
is a regular expression matcher, not a syntax highlighter :). You'll have to use multiple invocations of grep
, using a different value of GREP_COLOR
for each.
GREP_COLOR="1;32" grep foo file.txt | GREP_COLOR="1;36" grep bar
That would highlight "foo" and "bar" in different colors in lines that match both. I don't think there is a (simple) way to handle all occurrences of either pattern, short of merging the output stream of two independent calls:
{ GREP_COLOR="1;32" grep foo file.txt
GREP_COLOR="1;36" grep bar file.txt
} | ...
which will obviously look different than if there were a way to assign a separate color to each regular expression.
You can use awk
to substitute each match with itself wrapped in the correct control code.
echo "foo bar" | awk '{ gsub("bar", "\033[1;33m&\033[0m");
gsub("foo", "\033[1;36m&\033[0m"); print }'
In each line, you globally replace anything matching the given regular expression with itself (&
) wrapped in the ANSI escape sequences for desired color (which grep --color
does for you). After processing all of the possible matches, you need to explicitly print the line.
You can cascade greps with different colors by specifying --color=always and using the regular expression 'foo|$' to pass all lines.
For example:
tail -f myfwlog | GREP_COLOR='01;36' egrep --color=always 'ssh|$' | GREP_COLOR='01;31' egrep -i --color=always 'drop|deny|$'
If you want the entire line to be highlighted, update your regular expression accordingly:
.... GREP_COLOR='01;31' egrep -i --color=always '^.*drop.*$|^.*deny.*$|$'