Using the while loop

Similar to C programming, awk has a while loop for doing tasks repeatedly. while will check for the condition. If the condition is true, then actions will be performed. If a condition is false, then it will terminate the loop.

The syntax is as follows:

  while(condition) 
    actions 

An example of using the while construct in awk is as follows:

    $ cat people.txt
    $ awk '{ i  = 1; while ( i <= NF ) { print NF, $i ; i++ } }' people.txt

NF is the number of fields in the record. The variable i is initialized to 1. Then, while i is smaller or equal to NF, the print action will be performed. The print command will print fields from the record from the people.txt file. In the action block, i is incremented by one. The while construct ...

Get Learning Linux Shell Scripting - Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.