awk Help: quick and easy question may be: How to use &&

Hi Guru's.

I am trying to use to check if $5 is greater than 80 & if not 100, then to print $0 :

awk '{ if ($5>80) && if ($5 != 100) print $0}

But getting error:

>bdf1|sed 's/%//g'|awk '{ if ($5>80) && if ($5 != 100) print $0}'
 syntax error The source line is 1.
 The error context is
                { if ($5>80) >>>  && <<< 
 awk: The statement cannot be correctly parsed.
 The source line is 1.

Please advise how to use two condition within awk,
Thanks a lot,

[root@host ~]# echo "a a a a 80 a" | awk '( $5 > 80 ) && ( $5 != 100 ) { print $0 }'
[root@host ~]# echo "a a a a 99 a" | awk '( $5 > 80 ) && ( $5 != 100 ) { print $0 }'
a a a a 99 a
[root@host ~]# echo "a a a a 100 a" | awk '( $5 > 80 ) && ( $5 != 100 ) { print $0 }'
[root@host ~]# echo "a a a a 101 a" | awk '( $5 > 80 ) && ( $5 != 100 ) { print $0 }'
a a a a 101 a

Also

awk '$5>80&&$5!=100{print $0}' filename

OR

awk '{if(($5>80)&&($5!=100)) print $0 } ' filename
1 Like

Indeed - I include the parenthesis and spaces for readability, though due to rules of precedence they aren't required.

Thanks, ( zazzybob && bipinajith ) , great answers, I like both, however the short one from bipinajith is great.

awk '$5>80&&$5!=100' filename

As you want to print the entire line, we dont need to use print $0

I think it's best to be a little more verbose when specifying commands like this - especially within scripts. A year later when you come back to look at this (especially since you are asking for help in the first place), you might not understand what:

awk '$5>80&&$5!=100' filename

is doing, whereas

awk '( $5 > 80 ) && ( $5 != 100 ) { print $0 }' filename

is more readable.

Of course - all solutions are technically correct, and this is just personal opinion - but after 20 years of looking at others' shell scripts, readability is worth a few extra key strokes. On the command line, not so much.

Cheers,
ZB

2 Likes