gawk: Nonconstant Fields

1 
1 4.3 Nonconstant Field Numbers
1 =============================
1 
1 A field number need not be a constant.  Any expression in the 'awk'
1 language can be used after a '$' to refer to a field.  The value of the
1 expression specifies the field number.  If the value is a string, rather
1 than a number, it is converted to a number.  Consider this example:
1 
1      awk '{ print $NR }'
1 
1 Recall that 'NR' is the number of records read so far: one in the first
1 record, two in the second, and so on.  So this example prints the first
1 field of the first record, the second field of the second record, and so
1 on.  For the twentieth record, field number 20 is printed; most likely,
1 the record has fewer than 20 fields, so this prints a blank line.  Here
1 is another example of using expressions as field numbers:
1 
1      awk '{ print $(2*2) }' mail-list
1 
1    'awk' evaluates the expression '(2*2)' and uses its value as the
1 number of the field to print.  The '*' represents multiplication, so the
1 expression '2*2' evaluates to four.  The parentheses are used so that
1 the multiplication is done before the '$' operation; they are necessary
1 whenever there is a binary operator(1) in the field-number expression.
1 This example, then, prints the type of relationship (the fourth field)
1 for every line of the file 'mail-list'.  (All of the 'awk' operators are
1 listed, in order of decreasing precedence, in ⇒Precedence.)
1 
1    If the field number you compute is zero, you get the entire record.
1 Thus, '$(2-2)' has the same value as '$0'.  Negative field numbers are
1 not allowed; trying to reference one usually terminates the program.
1 (The POSIX standard does not define what happens when you reference a
1 negative field number.  'gawk' notices this and terminates your program.
1 Other 'awk' implementations may behave differently.)
1 
1    As mentioned in ⇒Fields, 'awk' stores the current record's
11 number of fields in the built-in variable 'NF' (also ⇒Built-in
 Variables).  Thus, the expression '$NF' is not a special feature--it
1 is the direct consequence of evaluating 'NF' and using its value as a
1 field number.
1 
1    ---------- Footnotes ----------
1 
1    (1) A "binary operator", such as '*' for multiplication, is one that
1 takes two operands.  The distinction is required because 'awk' also has
1 unary (one-operand) and ternary (three-operand) operators.
1