Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk OR statement

Tags:

awk

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?

like image 797
Numpty Avatar asked Apr 05 '13 17:04

Numpty


People also ask

What is awk command used for?

Awk is mostly used for pattern scanning and processing. It searches one or more files to see if they contain lines that matches with the specified patterns and then perform the associated actions. Awk is abbreviated from the names of the developers – Aho, Weinberger, and Kernighan.

What is awk '{ print $3 }'?

txt. If you notice awk 'print $1' prints first word of each line. If you use $3, it will print 3rd word of each line.

What does awk '{ print $2 }' mean?

awk '{ print $2; }' prints the second field of each line. This field happens to be the process ID from the ps aux output.


2 Answers

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

awk '{if ($2=="abc" || $2=="def") print "blah" }' 
like image 137
P.P Avatar answered Sep 19 '22 22:09

P.P


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.

like image 33
Ed Morton Avatar answered Sep 20 '22 22:09

Ed Morton