Conditional if clause in awk

awkgawktext processing

Please consider below file:

foo,1000,boo,A
foo,1000,boo,B
foo,1001,boo,B
foo,1002,boo,D

And we have below rules:

If $2 equal 1000, $4 should be equal A
If $2 equal 1001, $4 should be equal B
If $2 equal 1002, $4 should be equal C

I want to apply the above rules to a single awk command, where if $4 does not obey, print the record.

The desired output would be:

foo,1000,boo,B
foo,1002,boo,D

I tried with:

awk -F, '{if(($2==1000 && $4!=A) || ($2==1001 && $4!=B) || ($4==1002 && $4!=C)){print $0}}'

Best Answer

Use this:

awk -F, '($2==1000 && $4!="A") || ($2==1001 && $4!="B") || ($2==1002 && $4!="C")' file

In the curvy brachets are the 3 conditions; if one of them applies the line will be printed. The conditions inside the brackets are connected with a AND, so both must apply.

Related Question