Low Orbit Flux Logo 2 F

awk if else

We are going to show you how to use if/else with awk. We are going to pipe info from another command but you could also operate directly on a file. Most of the examples are shown as one line commands.

Here is a basic awk example without if/else logic:


ps -ef | awk '{ print $3 }'

Here is an awk command that uses the if statement:


ps -ef | awk '{ if( $3 < 100 ) { print $3 } }'

Here is a slightly more complicated command that includes both an if and an else in the command:


ps -ef | awk '{ if( $3 < 100 ) { print "Low: "  $3 } else { print "High: " $3 } }'

Here we have even more complicated syntax that includes if, else if, and else:


ps -ef | awk '{ if( $3 < 100 ) { print "Low: "  $3 } else if( $3 >= 4000 ) { print "High: " $3 } else { print "Medium: " $3 } }'

This is how it would look expanded:


ps -ef | awk '{ 
if( $3 < 100 ) 
{ 
    print "Low: "  $3 
} 
else if( $3 >= 4000 ) 
{ 
    print "High: " $3 
} 
else 
{ 
    print "Medium: " $3 
} }'