Search code examples
bashcolorssedawkgrep

Grep output with multiple Colors?


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.


Solution

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