Actual Application of awk: Text Merge
Use the awk command to combine the two lines with the same names in the following two files
[Root @ localhost ~] # Cat 1.txt
Han Hailin, 21 years old
Hai linhan, 23 years old
Han Linhai, 22 years old
Lin haihan, 24 years old
[Root @ localhost ~] # Cat 2.txt
Han Linhai male
Hai Lin Han Nan
Han Hailin male
Lin haihan Nan
Output result:
Han Hailin, 21, male
[Root @ localhost ~] # Awk 'nr = FNR {a [$1] = $2} NR> FNR {print $0, a [$1]} '2.txt 1.txt
Han Hailin, 21, male
23-year-old male Hailin Han
Han Linhai, 22, aged male
Lin haihan, 24, male
[Root @ localhost ~] # Awk 'nr = FNR {a [$1] = $2} NR> FNR {print $0, a [$1]} '2.txt 1.txt> 3.txt
[Root @ localhost ~] # Cat 3.txt
Han Hailin, 21, male
23-year-old male Hailin Han
Han Linhai, 22, aged male
Lin haihan, 24, male
Explanation:
In awk, NR and FNR have similar meanings. The only difference is the range of their functions. NR is the count of all read row information, while FNR is the row information count of the file being read, FNR starts counting again from 0 during file switching, so the preceding statement indicates:
NR = the value of FNR nr1_is 4. The value of fnris 1-4. The first data item of 2.txt is the key, and $2 is an array consisting of 2nd columns;
In an array consisting of NR> FNR records, if the rows are located, the rows are printed and the array items are added.
NR is short for the English number of record, that is, every time an awk reads a row of data from a file or input stream, this variable is added. This is the variable that comes with awk.
Other explanations:
NR = FNR {a [$1] = $2}
Open the first 2.txt file and store the $2 column in the file to the array a [$1.
NR> FNR {print $0, a [$1]}
After that, open the second file, print the 1.txt line of content, and then print the content of the first file a [$1] array.
When adding ifenders, it is easier to understand. The order allows you to skip the first column of 1.txt in array a, and print the entire line of content and a [$1] array content;
[Root @ localhost ~] # Awk 'nr = FNR {a [$1] = $2; next} NR> FNR {if ($1 in a) print $0, a [$1]} '2.txt 1.txt
Han Hailin, 21, male
23-year-old male Hailin Han
Han Linhai, 22, aged male
Lin haihan, 24, male
The file order is different and the results are different;
[Root @ localhost ~] # Awk 'nr = FNR {a [$1] = $2} NR> FNR {print $0, a [$1]} '1.txt 2.txt
Han Linhai, 22 years old
Hai Lin Han, 23 years old
Han Hailin, 21 years old
Lin haihan, 24 years old
Awk value assignment operator
Awk escape sequence and Arithmetic Operator
Introduction and use of AWK
AWK introduction and Examples
Shell script-AWK text editor syntax
Learning and using AWK in Regular Expressions
AWK diagram of Text Data Processing
How to Use the awk command in Linux
Text Analysis Tool-awk
This article permanently updates the link address: