AWK - Control Flow


Advertisements

Like other programming languages, AWK provides conditional statements to control the flow of a program. This chapter explains AWK's control statements with suitable examples.

If statement

It simply tests the condition and performs certain actions depending upon the condition. Given below is the syntax of if statement −

Syntax

if (condition)
   action

We can also use a pair of curly braces as given below to execute multiple actions −

Syntax

if (condition) {
   action-1
   action-1
   .
   .
   action-n
}

For instance, the following example checks whether a number is even or not −

Example

[jerry]$ awk 'BEGIN {num = 10; if (num % 2 == 0) printf "%d is even number.\n", num }'

On executing the above code, you get the following result −

Output

10 is even number.

If Else Statement

In if-else syntax, we can provide a list of actions to be performed when a condition becomes false.

The syntax of if-else statement is as follows −

Syntax

if (condition)
   action-1
else
   action-2

In the above syntax, action-1 is performed when the condition evaluates to true and action-2 is performed when the condition evaluates to false. For instance, the following example checks whether a number is even or not −

Example

[jerry]$ awk 'BEGIN {
   num = 11; if (num % 2 == 0) printf "%d is even number.\n", num; 
      else printf "%d is odd number.\n", num 
}'

On executing this code, you get the following result −

Output

11 is odd number.

If-Else-If Ladder

We can easily create an if-else-if ladder by using multiple if-else statements. The following example demonstrates this −

Example

[jerry]$ awk 'BEGIN {
   a = 30;
   
   if (a==10)
   print "a = 10";
   else if (a == 20)
   print "a = 20";
   else if (a == 30)
   print "a = 30";
}'

On executing this code, you get the following result −

Output

a = 30
Advertisements