Use the awk command to merge the two lines with the same name in the following two files.
[[email protected] ~]# cat 1.txt Han Hailin 21-year-old Hailin Han 23-year-old Han Linhai 22-year-old Lin Han 24-year-old [[email protected] ~]# cat 2.txt Han Linhai male hailin Han Nan Han Hailin male Linhai Han Nan
Output effect:
Han Hailin 21-year-old male
[[email protected] ~]# awk ' nr==fnr{a[$1]=$2}nr>fnr{print $0,a[$1]} ' 2.txt 1.txt Han Hailin 21-year-old male Hailin Han 23-year-old male Han Linhai 22-year-old male Lin Hai Han 24-year-old male
[[Email protected]~]# awk ' nr==fnr{a[$1]=$2}nr>fnr{print $0,a[$1]} ' 2.txt 1.txt > 3.txt[[email protected] ~]# Cat 3 . txt Han Hailin 21-year-old male 23-year-old male Han Linhai 22-year-old man Lin Hai Han 24-year-old male
Explain:
In Awk, nr and Fnr are similar, the only difference is the scope, NR is all read the row information count, and FNR is reading the file of the row information count, FNR in the file switch will restart from 0 count, so the above statement means:
NR==FNR NR The maximum value is 4,FNR value of 1-4, the first data item in 2.txt is Key,$2, which is the 2nd column data array;
Nr>fnr at this time nr= (Total row number of 2.txt +fnr), nr maximum value of 8,FNR is re-counted from 1-4, to determine the first data item in an array that is not in 2.txt data, if so, print the bank addend group item.
NR is a shorthand for the English number of record, which is the addition of this variable to awk every time a row of data is read from a file or input stream. This is the variable that awk comes with.
Other explanations:
NR==FNR{A[$1]=$2}
Open the first file 2.txt, the contents of the file inside the content of the list to a[$1] this array.
Nr>fnr{print $0,a[$1]}
Then open the second file, print a 1.txt line of content, and then print the contents of the first file a[$1] array.
Add if judgment, easier to understand, the above command omitted; Judge the first column of 1.txt in the A array, print the whole line content and a[$1] array contents;
[[email protected] ~]# awk ' nr==fnr{a[$1]=$2;next}nr>fnr{if ($ in a) print $0,a[$1]} ' 2.txt 1.txt Han Hailin 21-year-old male Hailin Han 23-year-old man Han Linhai 22-year-old man Lin Hai Han 24-year-old man
The file order is different and the result is different;
[[email protected] ~]# awk ' nr==fnr{a[$1]=$2}nr>fnr{print $0,a[$1]} ' 1.txt 2.txt Han Linhai male 22 Han Nan 23-year-old Han Hailin male 21-year-old Lin Hai Han male 24-year-old
This article is from the "Model Student's Learning blog" blog, please be sure to keep this source http://mofansheng.blog.51cto.com/8792265/1671764
awk actual application: Text merge