awk FNR - The Current Record Number being processed


Example

FNR contains the number of the input file row being processed. In this example you will see awk starting on 1 again when starting to process the second file.

Example with one file

$ cat file1
AAAA
BBBB
CCCC
$ awk '{ print FNR }' file1
1
2
3

Example with two files

$ cat file1
AAAA
BBBB
CCCC
$ cat file2
WWWW
XXXX
YYYY
ZZZZ
$ awk '{ print FNR, FILENAME, $0 }' file1 file2
1 file1 AAAA
2 file1 BBBB
3 file1 CCCC
1 file2 WWWW
2 file2 XXXX
3 file2 YYYY
4 file2 ZZZZ

Extended example with two files

FNR can be used to detect if awk is processing the first file since NR==FNR is true only for the first file. For example, if we want to join records from files file1 and file2 on their FNR:

$ awk 'NR==FNR { a[FNR]=$0; next } (FNR in a) { print FNR, a[FNR], $1 }' file1 file2
1 AAAA WWWW
2 BBBB XXXX
3 CCCC YYYY

Record ZZZZ from file2 is missing as FNR has different max value for file1 and file2 and there is no join for differing FNRs.