Conditional Statements

A conditional statement allows you to make a test before performing an action. In the previous chapter, we saw examples of pattern matching rules that were essentially conditional expressions affecting the main input loop. In this section, we look at conditional statements used primarily within actions.

A conditional statement is introduced by if and evaluates an expression placed in parentheses. The syntax is:

if ( expression )
   action1
[else
   action2]

If expression evaluates as true (non-zero or non-empty), action1 is performed. When an else clause is specified, action2 is performed if expression evaluates to false (zero or empty). An expression might contain the arithmetic, relational, or Boolean operators discussed in Chapter 7.

Perhaps the simplest conditional expression that you could write is one that tests whether a variable contains a non-zero value.

if ( x ) print x

If x is zero, the print statement will not be executed. If x has a non-zero value, that value will be printed. You can also test whether x equals another value:

if ( x == y ) print x

Remember that “==” is a relational operator and “=” is an assignment operator. We can also test whether x matches a pattern using the pattern-matching operator “~”:

if ( x ~ /[yY](es)?/ ) print x

Here are a few additional syntactical points:

  • If any action consists of more than one statement, the action is enclosed within a pair of braces.

      if ( expression ) { 
      	statement1
      	statement2
      }

    Awk is not very particular ...

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.