Other Statements That Affect Flow Control

The if, while, for, and do statements allow you to change the normal flow through a procedure. In this section, we look at several other statements that also affect a change in flow control.

There are two statements that affect the flow control of a loop, break and continue. The break statement, as you’d expect, breaks out of the loop, such that no more iterations of the loop are performed. The continue statement stops the current iteration before reaching the bottom of the loop and starts a new iteration at the top.

Consider what happens in the following program fragment:

for ( x = 1; x <= NF; ++x )
	if ( y == $x ) {
		print x, $x
		break
	}
print

A loop is set up to examine each field of the current input record. Each time through the loop, the value of y is compared to the value of a field referenced as $x. If the result is true, we print the field number and its value and then break from the loop. The next statement to be executed is print. The use of break means that we are interested only in the first match on a line and that we don’t want to loop through the rest of the fields.

Here’s a similar example using the continue statement:

for ( x = 1; x <= NF; ++x ) {
	if ( x == 3 ) 
		continue
	print x, $x
}

This example loops through the fields of the current input record, printing the field number and its value. However (for some reason), we want to avoid printing the third field. The conditional statement tests the counter variable and if it is equal ...

Get sed & awk, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.