Awk NR Example: Number of Records VariableAwk NR gives you the total number of records being processed or the current line number. In the following awk
NR example, NR variable is the line number, but then later in the END section awk NR tells you the total number of records in a file.$ awk '{print "counted line - ",NR;}END {print NR, "Total lines in file";}' file1.txt counted line - 1 counted line - 2 counted line - 3 counted line - 4 4 Total lines in file or confirming the input file $ cat file1.txt GERMANY FRANCE UK POLLAND Then showing that NR can be the current line (record) being processed: $ awk '{print "counted line - ",NR;}' file1.txt counted line - 1 counted line - 2 counted line - 3 counted line - 4 and it can also be the last record being processed, or the total number of records to process. $ awk 'END {print NR, "Total lines in file";}' file1.txt 4 Total lines in file When awk reads from the multiple input files, the awk
NR variable will give the total number of records relative to all the input file. In other words, since Awk's default is each line in an input file is a record, NR is the total number of lines in the input file, or the total number of records. When dealing with multiple files, NR is the total number of records (or total number of lines) of all the input files put together. Awk
FNR will give you the number of records for each input file. So the NR is the list of all the records in all the files combined, and FNR is just the number of records in one of the files. $ awk '{print FILENAME, FNR;}' student-marks bookdetails student-marks 1 student-marks 2 student-marks 3 student-marks 4 student-marks 5 bookdetails 1 bookdetails 2 bookdetails 3 bookdetails 4 bookdetails 5 In the above example, instead of awk FNR, if you use awk NR, for the file bookdetails the you will get from 6 to 10 for each record.
or confirming the input files: $ cat file1.txt GERMANY FRANCE UK POLLAND $ cat file2.txt POLLAND GERMANY and then running the FNR version. Notice how it counts the total number of lines (records) for the first file, then starts over for the second file? $ awk '{print FILENAME, FNR;}' file1.txt file2.txt file1.txt 1 file1.txt 2 file1.txt 3 file1.txt 4 file2.txt 1 file2.txt 2 And then replacing FNR with NR to better understand the differences. Here NR counts the total, and does not reset the count when it is working with a second file. $ awk '{print FILENAME, NR;}' file1.txt file2.txt file1.txt 1 file1.txt 2 file1.txt 3 file1.txt 4 file2.txt 5 file2.txt 6 References
|