Go to the first, previous, next, last section, table of contents.


The next Statement

The next statement forces awk to immediately stop processing the current record and go on to the next record. This means that no further rules are executed for the current record. The rest of the current rule's action is not executed either.

Contrast this with the effect of the getline function (see section Explicit Input with getline). That too causes awk to read the next record immediately, but it does not alter the flow of control in any way. So the rest of the current action executes with a new input record.

At the highest level, awk program execution is a loop that reads an input record and then tests each rule's pattern against it. If you think of this loop as a for statement whose body contains the rules, then the next statement is analogous to a continue statement: it skips to the end of the body of this implicit loop, and executes the increment (which reads another record).

For example, if your awk program works only on records with four fields, and you don't want it to fail when given bad input, you might use this rule near the beginning of the program:

NF != 4 {
  err = sprintf("%s:%d: skipped: NF != 4\n", FILENAME, FNR)
  print err > "/dev/stderr"
  next
}

so that the following rules will not see the bad record. The error message is redirected to the standard error output stream, as error messages should be. See section Special File Names in gawk.

According to the POSIX standard, the behavior is undefined if the next statement is used in a BEGIN or END rule. gawk will treat it as a syntax error. Although POSIX permits it, some other awk implementations don't allow the next statement inside function bodies (see section User-defined Functions). Just as any other next statement, a next inside a function body reads the next record and starts processing it with the first rule in the program.

If the next statement causes the end of the input to be reached, then the code in any END rules will be executed. See section The BEGIN and END Special Patterns.

Caution: Some awk implementations generate a run-time error if you use the next statement inside a user-defined function (see section User-defined Functions). gawk does not have this problem.


Go to the first, previous, next, last section, table of contents.