How to Tail -f output with colors using only Awk and show the rest of the output

awklogstail

I was able to do a tail -f output with colors using the awk command. But I'm unsure how to output the rest of the log as it seems to be filtering only those 2 lines. I also want to see the other lines as the log is written.

What do I need to put in the awk command to show the rest of the output?

Image of my issue. The red text above is without using awk and displays the entire tail -f log. And below that is the same command with the awk color filtering.

enter image description here

Best Answer

Instead of printing matching lines with decorations, decorate matching lines, and print everything:

awk '/User@Host:/ { $0 = "\033[32m" $0 "\033[39m" }; /Query_time:/ { $0 = "\033[29m" $0 "\033[39m" }; 1'

This awk program consists of three patterns and associated actions:

  • lines matching User@Host: are processed with $0 = "\033[32m" $0 "\033[39m", which surrounds the current line with the given escape codes;
  • lines matching Query_time: are processed with $0 = "\033[29m" $0 "\033[39m";
  • lines for which the pattern 1 is non-zero (so all lines) are processed with the default action, which is to print the current line.

These are cumulative: all actions whose patterns match the current line are executed, in the order in which they are defined. A line matching User@Host: is modified (first action) and printed (third action). A line matching Query_time: is modified (second action) and printed (third action). A line matching neither is printed (third action).

That's the simplest technique to print all lines, without having to keep track of whether a line has been processed yet (to avoid printing a line twice). Instead of printing something in every set of action statements, we modify the current line as appropriate, and only print it once (but always print it).

Related Question