awk ternary condition judgment and examples
May 31, 2020
Awk ternary condition judgment is similar to the awk if else statement, providing branch control capability, and different branches perform different actions.
Ternary syntax
( Statement ) ? True : False ;
Ternary example
In the following example, we use the awk -F option or awk FS variable to separate the input strings according to the delimiter “:”, and then compare the field value size through the ternary and print the conditional branch content.
➜ ~ echo "1:2:983" | awk 'BEGIN{FS=":"}{res=$3>11?"ok":"not";print $2,res;}'
2 ok
➜ ~ echo "1:2:983" | awk 'BEGIN{FS=":"}{res=$1>11?"ok":"not";print $2,res;}'
2 not
Ternary and if else
Awk Ternary and awk if else are equivalent.
Ternary:
( Statement ) ? True : False ;
If-else:
if( Statement ) {
True;
} else {
False;
}
So for the above ternary example, we can also use if else.
➜ ~ echo "1:2:983" | awk 'BEGIN{FS=":"}{if($1>11){print "ok"}else{print "not"}}'
not
All right.
I think you will already use the awk ternary and its relationship with awk if else.