NRFNR in awk
In shell programming, awk is a powerful tool. You can think of it as a part of shell or a separate language with powerful functions. Let's talk about NR and FNR today.
Prepare two files first:
1. txt with the following content:
User password
Wolf 123456
Zys 123
2. txt content:
Id user
0001 wolf
0002 xiaozhai
In fact, when processing a single file, NR is the same as FNR, indicating the row number currently read, for example, run awk '{print NR}' 1.txt and run awk '{print FNR}' 1.txt, and the results are the same.
1
2
3
However, when processing two files, awk first reads the first file. At this time, NR is equal to FNR. However, when reading the second file, FNR starts counting again, while NR continues to grow, this is not the same,
Run awk '{print NR "\ t" FNR}' 1.txt 2. The txt result is as follows:
1 1
2 2
3 3
4 1
5 2
6 3
Password in begin, and the user name and password are printed. awk 'nr = FNR {a [$1] = $2; next} {if (a [$2]) {print $2 "\ t" a [$2] ;}' 1.txt 2.txt. Be sure to use single quotation marks and the result is:
User passwd
Wolf 123456
Explain this command: In the "users" column of "tables", if there is a record corresponding to the user of the current row in array a, print the user (that is, $2) and passwd (that is, a [$2]).
Awk functions are really powerful.