≡ Menu

Caught In the Loop? Awk While, Do While, For Loop, Break, Continue, Exit Examples

Linux Awk For, While Loop ExamplesThis article is part of the on-going Awk Tutorial Examples series. In our earlier awk articles, we discussed about awk print, awk user-defined variables, awk built-in variables, awk operators, and awk conditional statements.

In this article, let us review about awk loop statements – while, do while, for loops, break, continue, and exit statements along with 7 practical examples.

Awk looping statements are used for performing set of actions again and again in succession. It repeatedly executes a statement as long as condition is true. Awk has number of looping statement as like ‘C’ programming language.

Awk While Loop

Syntax:

while(condition)
	actions
  • while is a keyword.
  • condition is conditional expression
  • actions are body of the while loop which can have one or more statement. If actions has more than one statement, it has to be enclosed with in the curly braces.

How it works?Awk while loop checks the condition first, if the condition is true, then it executes the list of actions. After action execution has been completed, condition is checked again, and if it is true, actions is performed again. This process repeats until condition becomes false. If the condition returns false in the first iteration then actions are never executed.

1. Awk While Loop Example: Create a string of a specific length

$awk 'BEGIN { while (count++<50) string=string "x"; print string }'
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

The above example uses the ‘BEGIN { }’ special block that gets executed before anything else in an Awk program. In this block, awk while loop appends character ‘x’ to variable ‘string’ 50 times. count is a variable which gets incremented and checked it is less than 50. So after 50 iteration, this condition becomes false.
After it has looped, the ‘string’ variable gets printed out. As this Awk program does not have a body, it quits after executing the BEGIN block.

Awk Do-While Loop

How it works?Awk Do while loop is called exit controlled loop, whereas awk while loop is called as entry controlled loop. Because while loop checks the condition first, then it decides to execute the body or not. But the awk do while loop executes the body once, then repeats the body as long as the condition is true.

Syntax:

do
action
while(condition)

Even if the condition is false, at the beginning action is performed at least once.

2. Awk Do While Loop Example: Print the message at least once

$ awk 'BEGIN{
count=1;
do
print "This gets printed at least once";
while(count!=1)
}'
This gets printed at least once

In the above script, the print statement, executed at least once, if you use the while statement, first the condition will be checked after the count is initialized to 1, at first iteration itself the condition will be false,so print statement won’t get executed, but in do while first body will be executed, so it executes print statement.

Awk For Loop Statement

Awk for statement is same as awk while loop, but it is syntax is much easier to use.

Syntax:

for(initialization;condition;increment/decrement)
actions

How it works?Awk for statement starts by executing initialization, then checks the condition, if the condition is true, it executes the actions, then increment or decrement.Then as long as the condition is true, it repeatedly executes action and then increment/decrement.

3. Awk For Loop Example . Print the sum of fields in all lines.

$ awk '{ for (i = 1; i <= NF; i++) total = total+$i }; END { print total }'
12 23 34 45 56
34 56 23 45 23
351

Initially the variable i is initialized to 1, then checks if i is lesser or equal to total number of fields, then it keeps on adding all the fields and finally the addition is stored in the variable total. In the END block just print the variable total.

4. Awk For Loop Example: Print the fields in reverse order on every line.

$ awk 'BEGIN{ORS="";}{ for (i=NF; i>0; i--) print $i," "; print "\n"; }' student-marks
77  84  78  2143  Jones
45  58  56  2321  Gondrol
37  38  2122  RinRao
95  97  87  2537  Edwin
47  30  2415  Dayan

We discussed about awk NF built-in variable in our previous article. After processing each line, Awk sets the NF variable to number of fields found on that line.

The above script,loops in reverse order starting from NF to 1 and outputs the fields one by one. It starts with field $NF, then $(NF-1),…, $1. After that it prints a newline character.

Now let us see some other statements which can be used with looping statement.

Awk Break statement

Break statement is used for jumping out of the innermost looping (while,do-while and for loop) that encloses it.

5. Awk Break Example: Awk Script to go through only 10 iteration

$ awk 'BEGIN{while(1) print "forever"}'

The above awk while loop prints the string “forever” forever, because the condition never get fails. Now if you want to stop the loop after first 10 iteration, see the below script.

$ awk 'BEGIN{
x=1;
while(1)
{
print "Iteration";
if ( x==10 )
break;
x++;
}}'
Iteration
Iteration
Iteration
Iteration
Iteration
Iteration
Iteration
Iteration
Iteration
Iteration

In the above script, it checks the value of the variable “x”, if it reaches 10 just jumps out of the loop using break statement.

Awk Continue statement

Continue statement skips over the rest of the loop body causing the next cycle around the loop to begin immediately.

6. Awk Continue Example: Execute the loop except 5th iteration

$ awk 'BEGIN{
x=1;
while(x<=10)
{
if(x==5){
x++;
continue;
}
print "Value of x",x;x++;
}
}'
Value of x 1
Value of x 2
Value of x 3
Value of x 4
Value of x 6
Value of x 7
Value of x 8
Value of x 9
Value of x 10

In the above script, it prints value of x, at each iteration, but if the value of x reaches 5, then it just increment the value of x, then continue with the next iteration, it wont execute the rest body of the loop, so that value of x is not printed for the value 5. Continue statement is having the meaning only if you use with in the loop.

Awk Exit statement

Exit statement causes the script to immediately stop executing the current input and to stop processing input all the remaining input is ignored.

Exit accepts any integer as an argument which will be the exit status code for the awk process. If no argument is supplied, exit returns status zero.

7. Awk Exit Example: Exit from the loop at 5th iteration

$ awk 'BEGIN{
x=1;
while(x<=10)
{
if(x==5){
exit;}
print "Value of x",x;x++;
}
}'
Value of x 1
Value of x 2
Value of x 3
Value of x 4

In the above script, once the value of x reaches 5, it calls exit, which stops the execution of awk process. So the value of x is printed only till 4, once it reaches 5 it exits.

Recommended Reading

Sed and Awk 101 Hacks, by Ramesh Natarajan. I spend several hours a day on UNIX / Linux environment dealing with text files (data, config, and log files). I use Sed and Awk for all my my text manipulation work. Based on my Sed and Awk experience, I’ve written Sed and Awk 101 Hacks eBook that contains 101 practical examples on various advanced features of Sed and Awk that will enhance your UNIX / Linux life. Even if you’ve been using Sed and Awk for several years and have not read this book, please do yourself a favor and read this book. You’ll be amazed with the capabilities of Sed and Awk utilities.

Add your comment

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

Comments on this entry are closed.

  • Catalin February 24, 2010, 10:40 am

    I always liked the tutorials about awk. Always we found something new.

  • Hirade Nilesh July 30, 2010, 5:01 am

    Can i get AWK’s e-book………………

  • avinash October 21, 2010, 4:08 am

    Hi,
    If we want to enter the student details(name,age,address, etc,.) by user. But we genarate their roll numbers automatically in sequential manner.
    Ex: in command prompt it asks enter student name,–>avi
    enter age,–>20
    enter address–>hyderabad
    output: 1. avi 20 hyderabad
    second time we enter another student details it starts roll number from 2.Next time 3 and so on.

  • Simon June 21, 2012, 3:01 am

    There’s also the “for (x in y)” for loop construct, i.e. enumerate every value in array y, placing the index value in x, such that the user can act on each value in the array using y[x].

    It would also be useful to know what the equivalent in awk is to the bash “for x in a b c d; do” construct, where each of a, b, c & d can be acted on by using $x.

  • Elly December 7, 2016, 10:37 am

    Hi,

    Could you please help me with this? I want to make some instructions inside a loop for arch line in a file something like this:

    cat /ruta/file/GPRS/ESTCOL_GPRS_2016* | awk ‘BEGIN{FS=”,”;}{ for line in $( cat portals_GPRS.txt) do (if (substr($5,1,8)==’$DATE’) print $8) done;} END {}’| paste -s -d”+” |bc)

    But yet I have errors