First rule of coding is that awk code has to be ecapsulatied in an outer brace set. Only the pattern filters may appear outside of the braces.
if statement.
if ( condition ) { action action } else { action }
The else and else block is optional.
awk does not support the else-if, but other if statements can be embedded in the action block areas.
if ( $1 >= "b" && $1 < "c" ) { print $1 }
This would print all instances of field 1 that started with the letter b.
Uses ASCII ordering to do evaluation.
The ~ and !~ can be use both in the pattern area and in the coding blocks. It allows the use of /regex/ as an alterative conditional match.
When doing a regular expression match inside an action block, you must use flow of control commands. if, while, etc.
if ( $3 ~ /Gasoline/ ) { actions }
Quick conditional operator. awk provide the ? as a way to write a simple quick if/else statement.
grade = ( $1 > 65) ? "pass" : "fail"
will test field 1 for value greater than 65, if true, it will assign "pass" to variable grade. Else if false, it will assignm "fail".
while ( condition ) { actions }
The while loop runs condition before entering loop. It is possible that actions are never taken if no true condition found.
do { actions } while (condition)The do-while loop will always execute actions at least once.
for ( set-var; test-condition; adjustment ) { actions }The for loop does a controled loop sequence.
The three fields are all optional, but the semi-colons are required.
Given the awk script, pname.awk
{ for ( i = 8; i <= NF; ++i ) { printf ( "%s ", $i ); } printf ( "\n" ); }
which is invoked with ps -ef | awk -f pname.awk
This will print from 8th field on of the output of the ps -ef command. Because some programs listed were started with options, this will show both progam name and any other trailing arguments.