dollarint

A dollar sign and followed by an [[integer?]] are used to refer to fields within the current record:

 { print $3 }    # output field number three

Though you might consider $3 as a variable, it's not exactly true, in fact $ is the field reference operator and 3 is just a number that tells awk you want to reference the third field. They behave a bit like an array ie where with an array you would write fields[1] in awk you write $1

If you know C it behaves like the * on a pointer.

Field numbers are not limited to single digits

Unlike the positional parameters in the Unix shell, fields are not limited to single digits:

  { print $123 }    # output field number 123

Field numbers do not need to be constant

The field number after the $ does not need to be a [[constant?]].

Using a variable name to specify the field number

It is possible to use to use a [[variable_name?]] after the dollar sign to specify the field number:

 { myfield = 4
   print $myfield    # output field number 4
 }

Using an expression to specify the field number

It is also possible to use an expression after the dollar sign to specify the field number. Note that parentheses are used around the [[expression?]], to ensure evaluation of the [[expression?]] before the field number:

   print $(3 + 2)    # output field number 5
   # The parentheses above are important.
   # Without parentheses, we would get a value 2 more than field 3

A dollar sign followed by a zero references the entire record

A dollar sign and followed by a zero references the entire record:

 { print $0 }    # output the entire record

Referencing a non existent field

Reference a non existing field will produce an [[empty_string?]].

Field numbers must be positive

It is not permissible to use negative field numbers. Attempting to reference a negative field number will cause [[undefined_behaviour?]], or a [[fatal_error?]] will occur.

Assignment to dollarint variables

It is possible to change the contents of a field in the current record by making an assignment to the dollarint special variable:

{{{ awk { $2 = 23 } # Change field two to a value of 23 }}}

See also