Grep output with multiple Colors?

Evil Genius picture Evil Genius · Jun 21, 2013 · Viewed 45.1k times · Source

Is there an elegant method in bash for running grep against a text file with two or more patterns, and each pattern that matches is output in a different color?

So a line that matches on MALE and AUGUST would output MALE in blue and AUGUST in orange? I am open to the use of sed, awk, grep and crayons or others.

Answer

Rob Windsor picture Rob Windsor · Feb 28, 2014

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.*$|$'