Conditional and Looping Statements in AWK Programming Language

AWK is a command-based programming language that is used for text processing and report generation. Control statements help programmers and administrators to extract more precise information from data. If you have not read the beginners guide for awk programming, Click Here.  This article covers control statements which include conditional and looping statements.

Conditional Statements

  • if
  • switch

Loop Statements

  • while
  • do-while
  • for

Sample-file (student-marks)

Conditional statements

if statement

if statement syntax is similar to the C programming language.  You can check the condition here and accordingly display results. This statement help programmer to filter information from a large raw data.

Examples:

$awk 'BEGIN{ x=4; if ( x % 2 == 1) print x " is odd number" }'

$awk '{if($2>32 && $2<=69) print}' student-marks

switch statement

Switch statement only works with GAWK and not work with default awk. Statement syntax is similar to C programming language.

$ vi switch-example.awk 
BEGIN {
      p = "3";
      switch ( p ) {
             case "a" :
             print "p = a" 
             break
             case "3" :
             print "p = 20"
             break
             default :
             print "Not Found"
             break
                   }
}
$ awk -f switch-example.awk

Loop Statements

Loop statements in awk use for repetitive tasks.

while statement

$ vi while-example.awk
BEGIN  {
       i = 1
       while ( i <=10 ) 
       {
            print i
            i = i + 3
       }
}
$ awk -f while-example.awk

do-while statement

$ vi dowhile-example.awk
BEGIN    {
    x = 5;
    do 
    {
           print "x"
           x = x + 10
    }    
    while ( x <= 45 )
}
$ awk -f dowhile-example.awk

for statement

It is widely used by programmers and administrators to do a repetitive task on raw data.

$ vi for-example.awk
{
    x=0;
    for ( i=2; i <=5; i++ )
    {
    x = x + i
    }
    print "total : ", x;
}

$ awk -f for-example.awk 

Conclusion

In this article, we have discussed examples of control statements in awk. These examples help you to understand the concept and then apply them for text processing and report generation. We have seen conditional statements such as if...else if.. and looping statements such as while, do-while, and for.

Subscribe us to receive more such articles updates in your email.

If you have any questions, feel free to ask in the comments section below. Nothing gives me greater joy than helping my readers!

Disclaimer: This tutorial is for educational purpose only. Individual is solely responsible for any illegal act.

You may also like...

1 Response

  1. Rahul says:

    Examples are good …

Leave a Reply

Your email address will not be published.