Sams Teach Yourself Shell Programming in 24 Hours
(Publisher: Macmillan Computer Publishing)
Author(s): Sriranga Veeraraghavan
ISBN: 0672314819
Publication Date: 01/01/99

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 variable’s 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.

Summary

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

  Field editing
  Pattern specific actions
  Using STDIN as input
  Variables
  Numeric and assignment expressions
  Using flow control

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:

The UNIX Programming Environment by Brian Kernighan and Rob Pike (Prentice-Hall, 1984)
The AWK Programming Language by Alfred Aho, Peter Weinberger, and Brian Kernighan (Addison-Wesley, 1984)
The GNU Awk User’s Guide by Arnold Robbins (SCC, 1996)


Previous Table of Contents Next