Statements
Programming languages need to support sequential, conditional, and iterative execution. awk provides these features with statements borrowed largely from the C programming language. This section also covers the different statement types that are specific to awk.
Sequential Execution
Sequential execution is provided by lists of statements, written one per line, or separated by semicolons. The three lines:
n = 123 s = "ABC" t = s n
can also be written like this:
n = 123; s = "ABC"; t = s n
In one-liners, we often need the semicolon form, but in awk programs supplied from files, we usually put each statement on its own line, and we rarely need a semicolon.
Wherever a single statement is expected, a compound statement consisting of a braced group of statements can be used instead. Thus, the actions associated with awk patterns are just compound statements.
Conditional Execution
awk provides for conditional execution with the if
statement:
if (expression
)statement
1 if (expression
)statement
1 elsestatement
2
If the expression
is nonzero (true),
then execute statement
1. Otherwise, if there is an else
part, execute
statement
2. Each of
these statements may themselves be if
statements, so the general form of a
multibranch conditional statement is usually written like this:
if (expression
1)statement
1 else if (expression
2)statement
2 else if (expression
3)statement
3 ... else if (expression
k)statement
k elsestatement
k+1
The optional final else
is always associated with ...
Get Classic Shell Scripting 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.