Go to the first, previous, next, last section, table of contents.

Non-constant Field Numbers

The number of a field does not need to be a constant. Any expression in the awk language can be used after a `$' to refer to a field. The value of the expression specifies the field number. If the value is a string, rather than a number, it is converted to a number. Consider this example:

awk '{ print $NR }'

Recall that NR is the number of records read so far: one in the first record, two in the second, etc. So this example prints the first field of the first record, the second field of the second record, and so on. For the twentieth record, field number 20 is printed; most likely, the record has fewer than 20 fields, so this prints a blank line.

Here is another example of using expressions as field numbers:

awk '{ print $(2*2) }' BBS-list

awk must evaluate the expression `(2*2)' and use its value as the number of the field to print. The `*' sign represents multiplication, so the expression `2*2' evaluates to four. The parentheses are used so that the multiplication is done before the `$' operation; they are necessary whenever there is a binary operator in the field-number expression. This example, then, prints the hours of operation (the fourth field) for every line of the file `BBS-list'. (All of the awk operators are listed, in order of decreasing precedence, in section Operator Precedence (How Operators Nest).)

If the field number you compute is zero, you get the entire record. Thus, $(2-2) has the same value as $0. Negative field numbers are not allowed; trying to reference one will usually terminate your running awk program. (The POSIX standard does not define what happens when you reference a negative field number. gawk will notice this and terminate your program. Other awk implementations may behave differently.)

As mentioned in section Examining Fields, the number of fields in the current record is stored in the built-in variable NF (also see section Built-in Variables). The expression $NF is not a special feature: it is the direct consequence of evaluating NF and using its value as a field number.

Go to the first, previous, next, last section, table of contents.