The following list describes some of the important numeric built-in
variables:
- NR
- Contains the number of records that have been read so far. When awk is looking at the first record, NR has the value
1; when awk is looking at the second record, NR has
the value 2; and so on. In a BEGIN instruction, NR has
the value 0. In an END instruction, NR contains
the total number of records that were read. This instruction:
END { print NR }
prints the total number
of data records read by the awk program.
- FNR
- Is like NR, but it counts the number of records that
have been read so far from the current file.
When you give several data files on the awk command line, awk sets FNR back to 1 when it begins reading each new
file. Thus, a command such as:
{ printf "%d:%s\n",FNR,$0 }
prints the line number in the current file, followed by a colon,
followed by the contents of the current line.
- NF
- Gives the number of fields in the current record. For the hobbies file, NF is 4 for each line,
because there are four fields in each record. In an arbitrary text
file, NF gives the number of words on the current line
in the file; by default, awk assumes that blanks separate
the fields of a record, so it considers each word on a line to be
a separate field. Therefore, the program:
{ count = count + NF }
END { print count }
prints the total number of words in the
file.
Using these built-in variables, you can create more ambitious
awk commands.
awk 'NF == 1 {print}' file
prints those
records with precisely one field in them. There is no
–F option
specified for this command, so
awk assumes that blanks or
tab characters separate the fields. The foregoing command therefore
prints all lines that contain only one word (that is, one field).
awk '{print FNR ": " $0}' file
$0 stands for the entire record. The foregoing
command displays the contents of
file, putting
a line number and a colon before each line.
awk '/abc/ {print FILENAME ": " $0}' *.bas
examines all files that have the
.bas extension
in the working directory. It prints every line that contains the string
abc and also displays the filename, so you know which file contains
which lines.