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.
It simply tests the condition and performs certain actions depending upon the condition. Given below is the syntax of if statement −
if (condition) action
We can also use a pair of curly braces as given below to execute multiple actions −
if (condition) { action-1 action-1 . . action-n }
For instance, the following example checks whether a number is even or not −
[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 −
10 is even number.
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 −
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 −
[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 −
11 is odd number.
We can easily create an if-else-if ladder by using multiple if-else statements. The following example demonstrates this −
[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 −
a = 30