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)statement1 if (expression)statement1 elsestatement2
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 (expression1)statement1 else if (expression2)statement2 else if (expression3)statement3 ... else if (expressionk)statementk elsestatementk+1
The optional final else is always associated with ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access