![如何使用awk得到以下结果?](https://linux22.com/image/140096/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8awk%E5%BE%97%E5%88%B0%E4%BB%A5%E4%B8%8B%E7%BB%93%E6%9E%9C%EF%BC%9F.png)
我要提取两个文件的数据:
文件1.txt:
Type Number ID Element Email
Zed 21-2 9 Blade
文件2.txt:
Name Order Email_Address
Ken 19 [email protected]
Tom 21 [email protected]
Ray 23 [email protected]
如何将两个文件合并为一个文件,结果如下:
Type Number ID Element Email
Zed 21-2 9 Blade [email protected]
这是我之前尝试过的:
awk 'NR==1{print $0;next} NR==FNR{a[$2]=$1"\t"$3"\t"$4";next} {if($2 in a){print(a[$2]"\t"$3)}}' file1.txt file2.txt
我认为我无法得到结果,因为 if 语句有一些问题。我怎样才能得到想要的结果?
答案1
$ awk 'BEGIN{print "Type Number ID Element Email"}NR==FNR{Arr[$2]=$NF;next}{split($2,b,"-");if(b[1] in Arr){print $0,Arr[b[1]]}}' file2.txt file1.txt
Type Number ID Element Email
Zed 21-2 9 Blade [email protected]
Arr[$2]=$NF
-> 将电子邮件地址存储在具有第 2 列索引的数组中
split($2,b,"-")
--> 拆分第二列值并将其用于查找。
答案2
awk '
NR == FNR {email[$2] = $3; next}
FNR == 1 {print; next}
{
for (order in email)
if ($2 ~ "^" order "\\>") {
print $0, email[order]
break
}
}
' file2.txt file1.txt | column -t
Type Number ID Element Email
Zed 21-2 9 Blade [email protected]
^
该正则表达式在Number 字段的开头 ( ) 查找订单号,并带有字边界 ( \>
),以便 file2 中的订单号“21”与 file1 中的订单号“211-1”不匹配