Previous | Table of Contents | Next |
The for Statement
The for statement enables you to repeat commands a certain number of times. The for loop in awk is similar to the for loop in the C language.
The idea behind the for loop is that you keep a counter and that you test in each iteration of the loop. Every time the loop executes, the counter is incremented. This is quite different from the for loop in the shell, which executes a set of commands for each item in a list.
The basic syntax of the for loop is
for (initialize_counter; test_counter; increment_counter) { action }
Here initialize_counter initializes the counter variable, test_counter is an expression that tests the counter variables value, and increment_counter increments the value of the counter. The parentheses surrounding the expression used by the for loop are required.
The actions that should be performed, action, are any sequence of valid awk commands. The braces surrounding the action are required only for actions containing more than one statement, but I recommend that you always use them for the sake of clarity and maintainability.
A common use of the for loop is to iterate through the fields in a record and output them, possibly modifying each record in the process. The following for loop prints each field in a record separated by two spaces:
#!/bin/sh awk '{ for (x=1;x<=NF;x+=1) { printf "%s ",$x ; } printf "\n" ; }' fruit_prices.txt
Here you use NF to access the number of fields in the current record. You also use the field access operator, $, in conjunction with the variable x to access the value stored at a particular field.
In this chapter I have introduced programming in awk. It is one of the most powerful text filtering tools available in UNIX. By using awk, you can often modify and transform text in ways that are difficult or impossible using only the shell.
Some of the important topics that I have covered are
In addition to these topics, awk offers features such as multiple line editing, arrays, and functions. If you are interested in learning more about these topics, consult one of the following sources:
Previous | Table of Contents | Next |