AWK 比较以产生所需的合并输出

AWK 比较以产生所需的合并输出

我正在尝试使用 AWK 比较两个 csv 文件并根据比较结果生成合并输出。两个文件都有一个匹配的值,我可以让它在 data2 列 ($2) 中显示所需的值和匹配值 (data1-$1 data2-$4),但我想要的是 data2-$2 和 data1-$2。希望了解如何实现这一目标。

数据1.csv

dt-101,willow
dt-102,dogwood
dt-103b,redbud
dt-103a,plum
dt-104,cedar
ls-47,oak
ls-47a,pinoak
ls-47b,liveoak

数据2.csv

4001,00:00:00:01,eric,dt-101
4002,00:00:00:02,paul,dt-101
4003,00:00:00:03,steve,dt-103b
4004,00:00:00:04,mike,dt-104
4005,00:00:00:05,dave,ls-47b
4006,00:00:00:06,alex,dt-102
4007,00:00:00:07,adam,ls-47a

这是我正在使用的字符串

awk -F, -v OFS=, 'NR==FNR{a[$1]; next} {print $2,a[$4]}' data1.csv data2.csv

这是我得到的

00:00:00:01,dt-101
00:00:00:02,dt-101
00:00:00:03,dt-103b
00:00:00:04,dt-104
00:00:00:05,ls-47b
00:00:00:06,dt-102
00:00:00:07,ls-47a

但我想要的是

00:00:00:01,willow
00:00:00:02,willow
00:00:00:03,redbud
00:00:00:04,cedar
00:00:00:05,liveoak
00:00:00:06,dogwood
00:00:00:07,pinoak

答案1

$ awk -F, -v OFS=, 'NR==FNR{a[$1]=$2; next} {print $2,a[$4]}' data1.csv data2.csv

#Output

[GC@GC awk]$ ls
data1.csv  data2.csv
[GC@GC awk]$ awk -F, -v OFS=, 'NR==FNR{a[$1]=$2; next} {print $2,a[$4]}' data1.csv data2.csv
00:00:00:01,willow
00:00:00:02,willow
00:00:00:03,redbud
00:00:00:04,cedar
00:00:00:05,liveoak
00:00:00:06,dogwood
00:00:00:07,pinoak
[GC@GC awk]$ 

相关内容