LINUX AWK Tutorial Series | Chapter 7

Hello and welcome to AWK tutorial series, Hope till now you would have found the series interesting.

In this chapter, I am going to discuss loops in awk.

Looping

Looping helps to do a particular set of actions repeatedly until a certain condition is met.

Types of Loop in AWK

  • while
  • do .. while
  • for

Syntax

While Loop: until the condition is true the body of the while will be executed.

while (condition)
{
body
}

Do While Loop: Do until the condition is not met. So this means the code body will always be executed once every time.

do
{
body
}
while (condition)

For Loop: Condition and variable initialization is done at the time of the start of the loop.

for (init;condition;increment)
{
body
}


Remember that the loop will be executed on all records one by one.


Some important looping constructs are 

  • break
  • continue
  • exit

Example 1:

From the employee data file, I want to print only 2 fields for each line twice every time. I can use while loop in this scenario.

I am using a script file. i++ is used to increment the value of i with one.

[himanshu@oel7 AWK]$ cat command_file
BEGIN{FS=","}
{
i=1
while(i < 3){
print $1,$2
i++
}
}






Example 2:

Now same first example if I need to do using do-while

[himanshu@oel7 AWK]$ cat command_file
BEGIN{FS=","}
{
i=1
do
{
print $1,$2
i++
}
while(i < 3)
}





Try at home: Now in both the above examples try to change the value of i=3 rather than i=1 and then run both with a while and do-while loop. Observe whats the change. Any doubts, please ask in the comment sections.


Example 3:

Now the same examples if I need to do using for loop.


[himanshu@oel7 AWK]$ cat command_file
BEGIN{FS=","}
{
for (i=1;i<3;i++)
{
print $1,$2
}
}




Tips:

let say now in my file I have some comment lines and I want to skip them. and print other lines. 

Example below, I don't want to print lines which start with "#"


[himanshu@oel7 AWK]$ awk -F "," '{print}' Employee_Data.csv
#This is employee data
Bob,M,Human Resources,30000
Alice,F,Human Resources,45000
Mark,M,Human Resources,30000
Robin,M,Human Resources,20000
Maria,F,Human Resources,30000
Kevin,M,Human Resources,60000
Robert,M,Human Resources,420000
#End of employee data file




^#--> this means records starting with #.
{next} --> Skip that record


More chapters to continue

If you like please follow and comment