The book says:
NR, which represents the number of rows of data that awk reads after the program starts executing.
FNR, which is similar to NR, is different from the 0 FNR that awk accumulates every new file.
Here's a look at two examples:
1, same as the output result of a single file NR and FNR: awk ' {print nr,$0} ' file1
1 A b c D
2 a B d C
3 A C b d awk ' {print fnr,$0} ' file1
1 A b c D
2 a B d C
3 A C b d
2, but for multiple files: awk ' {print nr,$0} ' file1 file2
1 A b c D
2 a B d C
3 A C b d
4 AA BB cc DD
5 AA BB DD cc
6 aa cc BB dd awk ' {print fnr,$0} ' file1 file2
1 A b c D
2 a B d C
3 A C b d
1 AA bb cc DD
2 AA BB DD cc
3 AA cc BB DD
In looking at an example of the typical application of NR and Fnr:
There are now two file formats as follows: cat Account
John |000001
Dick |000002 Cat Cdr
000001|10
000001|20
000002|30
000002|15
The desired result is to print the username, account number and amount on the same line as follows:
John |000001|10
John |000001|20
Dick |000002|30
Dick |000002|15
Execute the following code AWK-F | ' nr==fnr{a[2]= 2]=0;next}{print a[1] "|" 1] "|" 2} ' account Cdr
Comments:
When NR=FNR is true, it is judged that the first file account is currently being read, and then uses the {a[2]= 2]=0;next} loop to save each line of records in the set to array A and uses the $2nd field as the subscript reference.
When NR=FNR is false, it is judged that the second file Cdr is currently read, then {a[2]= 2]=0;next} is skipped and the {print a[1] "|" is executed unconditionally for each row of the second file CDR. 1] "|" 2}, at this point the variable 1 is the first field in the second file, when you read the first file, take the first file. The second field, 1, is the first field in the second file, and the first file is taken as the first file, and the second field 2 is the same as the index. Therefore, you can use a[$1 to refer to an array here.