Mark occurrences of keyword with a different color

I have a program which spits out an output to stdout like:

[OK]      Something is ok
[OK]      Something else is also ok
[FAIL]    This does not look good
[FAIL]    Neither does this
[OK]      At least this is fine

To more easy spot the fails from the output I would like to mark the occurrences of the keyword FAIL with red without discarding the other messages. It would be nice if I could also highlight the OK keywords with green :).

Doing a pipe to egrep --color FAIL will only show the lines where the FAIL keyword is present.

Asked By: Theodor


Based on manatwork‘s brilliant little “or nothing” hack in the other question, I offer this, which adds the ability to get two highlight colors:

 $ myprogram | 
   GREP_COLORS='mt=01;32' egrep --color=always '[OK]|' | 
   GREP_COLORS='mt=01;31' egrep --color=always '[FAIL]|'

That is, you run grep over the output twice, with a different GREP_COLORS environment variable each time.

The ’01;32′ value means “bold green”, and the other means “bold red”. See the Wikipedia article on ANSI codes for more ideas.

Alas, this requires GNU grep version 2.5.3 or higher. Older versions of GNU grep supported a different coloring mechanism, but those versions have a bug that prevents you from using the feature in a pipeline more than once. BSD grep emulates the older GNU grep coloring mechanism, and it will work twice in a pipeline, but it yells about “empty sub-expression” due to the manatwork hack.

You can remove the backslashes at the end of the first two lines to make it all a single line. I’ve just split it here for clarity and to play nice with the SE page format.

Answered By: Warren Young

You can use multitail or ccze for this, both allow configs to describe regexps to match and colors.

Answered By: Netch

Based on Warren Young’s answer, I wrote this Python script that does the same thing more elegantly and with a lot less typing. So this is how you’d use that script:

cat yourfile | himul '[OK]' '[FAIL]'
Answered By: kirubakaran
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.