Linux – Bash – Perl – Colorize tail -f output

I tail out a lot of Linux log files, and sometimes I want to highlight when certain messages scroll on the screen. This one-liner will tail a log file and highlight the entire line when certain keywords or phrases (based on the regex).

tail -f | perl -pe 's/.*example1.*/\e[31m$&\e[0m/g; s/.*example2.*/\e[32m$&\e[0m/g'

Essentially, this uses Perl’s substitute to replace the line which matches the regex with an Escape sequence to colorize the output \e[31m$ then the line itself followed by an Escape sequence to turn off all text attributes \e[0m.

In the example above, ‘example1’ will be output with the text attribute of 31 which sets the foreground (text color) of red. Whereas ‘example2’ will be output with the text attribute of 32 which will set the text color to green. To see a table of color codes and other ANSI text attributes (like bold, background color, blink, etc) see  ANSI escape code on Wikipedia.