awk NR FNR difference
May 1, 2019
Linux awk command can use variables NR and FNR to process multiple files.
NR : ordinal number of the current record, multiple files self-increase
FNR : ordinal number of the current record in the current file
awk NR example
- Processing a file
➜ awk '{print "ordinal number: " NR " - " $0}' test1.txt

- Processing multiple files
➜ awk '{print "ordinal number: " NR " - " $0}' test1.txt test2.txt

awk FNR example
- Processing a file
➜ awk '{print "ordinal number: " NR " - " $0}' test1.txt

- Processing multiple files
➜ awk '{print "ordinal number: " FNR " - " $0}' test1.txt test2.txt

awk NR==FNR example
NR==FNR :
1. When reading two or more files, determine whether it is the first file.
2. Printing of file associated content.
1. Judge the first file
➜ awk '{if(NR==FNR) {print "No.1 :" FNR " ->" $0}else{print "No.2 :"FNR " ->"$0}}' test1.txt test2.txt

2. Printing of file associated content
Two documents:
➜ awk cat test4.txt
apple|00009
jerry|00008
➜ awk cat test5.txt
00009|55|09
00009|100|03
00009|59|04
00009|89|10
00008|55|09
00008|79|12
Want to get such a result:
apple|00009|55|09
apple|00009|100|03
apple|00009|59|04
apple|00009|89|10
jerry|00008|55|09
jerry|00008|79|12
➜ awk -F "|" '{if(NR==FNR){z[$2]=$1}else{print z[$1] "|" $0}}' test4.txt test5.txt

3 Comments
Does this work right if the first file is empty? (0 bytes)
When a single file is executed, it won’t work. Multiple files are executed, no problem.
awk ‘{print “ordinal number: ” NR ” – ” $0}’ test1.txt #not work
awk ‘{print “ordinal number: ” NR ” – ” $0}’ test1.txt test2.txt # work!