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


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).

  • What is the $0 variable for and how is that used? And what does the 1 at the end of the line represent? thanks – Patoshi パトシ May 18 '16 at 19:19
  • But how come you're able to print the entire section while I can only print the line i searched for? – Patoshi パトシ May 18 '16 at 19:58
  • @duckx I've updated my answer to explain how it works. My approach here is to print all lines, modifying those which need colouring before they're printed. – Stephen Kitt May 18 '16 at 20:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.