user53029
user53029

Reputation: 695

Awk: string negation with ANSI escape seqences

I have a function setup to tail a file in color.

function testtail {
tail -f -n100 $1 | awk '/SNMP/ {print "\033[1;33m" $0 "\033[39m"}' 
}

This works as expected and prints all lines that contain SNMP in my specified color but how would I tell awk to also negate any line with string SNMP so that lines that do NOT match SNMP prints in another color? I have tried:

function testtail {
tail -f -n100 $1 | awk '/SNMP/ {print "\033[1;33m" $0 "\033[39m"}' '!/SNMP/ {print "\033[1;34m" $0 "\033[39m"}'

}

And this:

function testtail {
tail -f -n100 $1 | awk '/SNMP/ {print "\033[1;33m" $0 "\033[39m"}' | awk '!/SNMP/ {print "\033[1;34m" $0 "\033[39m"}'

}

But neither work. How can I achieve this?

Upvotes: 2

Views: 233

Answers (1)

fedorqui
fedorqui

Reputation: 290025

To me it looks like you are looking for an if-else condition:

... | awk '{if ($0 ~ /SNMP/) {print "\033[1;33m" $0 "\033[39m"} else {print XXX}}'

Where XXX can be whatever you want.

Or more idiomatically:

... | awk '/SNMP/ {print "\033[1;33m" $0 "\033[39m"; next} {print XXX}' 

Since these are the strings you are printing:

  • "\033[1;33m" $0 "\033[39m"
  • "\033[1;34m" $0 "\033[39m"

You can in fact use a variable to set 33 or 34 and keep the rest untouched.

Upvotes: 2

Related Questions