Like other programming languages AWK also provides conditional
statement to control the flow of the program. This tutorial explain
AWK's condition statement with suitable example.
Below is the syntax of the if-else statement:
If statement
It simply tests the condition and performs certain action depending upon condition. Below is the syntax of the if statement:if (condition) actionWe can also use pair of curly braces as given below to execute multiple actions:
if (condition)
{
action-1
action-1
.
.
action-n
}
For instance below simple example checks whether 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.
If Else Statement
In if-else syntax we can provide the list of actions to be performed when the condition becomes false.Below is the syntax of the if-else statement:
if (condition) action-1 else action-2In above syntax action-1 is performed when condition evaluates to true and action-2 is performed when condition evaluates to false. For instance below simple example checks whether 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 the above code, you get the following result:11 is odd number.
If-Else-If Ladder
We can easily create if-else-if ladder by using multiple if-else statement. Below simple example illustrates 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 the above code, you get the following result:a = 30

No comments:
Post a Comment