Home » Linux » awk OR statement

awk OR statement

Posted by: admin November 30, 2017 Leave a comment

Questions:

Does awk have an OR statement i.e given the following snippet:

awk '{if ($2=="abc") print "blah"}'

Is it possible to add an OR statement so that if $2==abc OR def -> print?

Answers:

Yes. There’s logical OR || that you can use:

awk '{if ($2=="abc" || $2=="def") print "blah" }'

Questions:
Answers:

You would not write this code in awk:

awk '{if ($2=="abc") print "blah"}'

you would write this instead:

awk '$2=="abc" {print "blah"}'

and to add an “or” would be either of these depending on what you’re ultimately trying to do:

awk '$2~/^(abc|def)$/ {print "blah"}'

awk '$2=="abc" || $2=="def" {print "blah"}'

awk '
BEGIN{ split("abc def",tmp); for (i in tmp) targets[tmp[i]] }
$2 in targets {print "blah"}
'

That last one would be most appropriate if you have several strings you want to match.

Questions:
Answers:
awk '{if ($2=="abc" || $2=="def") print "blah"}'