Awk tutorial: awk NR FNR difference

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


More about Linux awk command: linux awk syntax and awk examples
More about Linux commands: Linux Commands Tutorial

2 Comments

Add a Comment

Your email address will not be published. Required fields are marked *