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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.