我要提取两个文件的数据:
文件1.txt:
Type Serial ID Element Hit_Possibility
Yasuo 19-2 19623 Hasaki
文件2.csv:
Date,Name,Order,Hit Possibility
12-Aug,Ken,1,256
12-Aug,Tom,19,498
12-Aug,Ray,36,753
如何将两个文件合并为一个文本文件,结果如下:
Type Serial ID Element Hit_Possibility
Yasuo 19-2 19623 Hasaki 498
这是我之前尝试过的:
awk -F "\"*,\"*" 'NR==1{print $0;next} NR==FNR{Arr[$2]=$NF;next}{split($2,b,"-");if(b[1] in Arr){print $0,Arr[b[1]]}}' file2.csv file1.txt
我认为由于 NR==FNR 部分我无法得到结果。如何得到我想要的结果文件?
答案1
你可以试试这个 awk:
awk -F, '
(NR==FNR)&&(NR>1){a[$3]=$4;next} # Get keys of file2 into array a
($2 in a){$0=$0 a[$2]} # If key in file1 is part of the array a, append value
NR!=1 # Print all lines of file1 and file2 except the header
' file2 FS='[ -]' file1
答案2
您可以稍微简化一下奥利夫的答案:
awk -F, '
NR==FNR {a[$3] = $4
next}
{print $0, a[$2]
}
' file2 FS='[ -]' file1
Type Serial ID Element Hit_Possibility
Yasuo 19-2 19623 Hasaki 498