【问题标题】:awk compare and append the matches into another fileawk 比较并将匹配项附加到另一个文件中
【发布时间】:2014-05-27 17:41:22
【问题描述】:

我想比较两个文件的第一列。如果匹配,则将第 1 列和第 2 列的对应值从第一个文件打印到第二个文件

file1
apple,1,2
orange,2,3
pine,3,4

file2
apple,2,2
orange,4,5

期望的输出
apple,2,2,1,2
orange,4,5,2,3

我能够通过 awk -F, 'NR==FNR{_1[$1]++;next}_1[$1]' file2 file1 找到匹配项,但不知道如何将 file1 值附加到 file2

【问题讨论】:

    标签: linux shell unix awk


    【解决方案1】:

    怎么样:

    join -t',' file2 file1
    

    如果你喜欢用 awk 来做:

    awk -F',' 'NR==FNR{a[$1]=$0;sub(/^[^,]*,/,"",a[$1]);next}$1 in a{print $0 FS a[$1]}' f1 f2
    

    【讨论】:

    • 感谢awk @kent,如果你能解释一下就太好了。连接命令不起作用 cat file2 apple,2,2 orange,4,5 cat file1 apple,1,2 pine,3,43 orange,2,3 join -t "," file2 file1 只给出 apple,2,2,1, 2 结果
    • @GanzRicanz 它(awk 的)非常简单,你没有得到哪一部分?
    【解决方案2】:

    你可以使用join:

    join -t "," file2 file1
    

    或扩展您的awk:

    awk -F, 'NR==FNR{_1[$1]++;_2[$1]=FS $2 FS $3;next}_1[$1]{print $0 _2[$1]}' file2 file1
    

    【讨论】:

    • 感谢 awk @mark,如果你能解释一下就太好了。加入命令不起作用 cat file2 apple,2,2 orange,4,5 cat file1 apple,1,2 pine,3,43 orange,2,3 join -t "," file2 file1 只给出 apple,2,2 ,1,2 结果
    • awk 和你的一样,只是它也将字段 2 和 3 存储在数组 _2[] 中,由字段分隔符 (FS) 分隔。然后,当它打印时,它会打印 file2 ($0) 中的整行以及从 file1 中保存的字段 2 和 3。
    • 我很惊讶“加入”命令不起作用。你的文件中有奇怪的字符吗?尝试运行“cat -vet file[12]”并查找 ^M。如果有,请尝试运行“dos2unix file1”等。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 2018-09-01
    相关资源
    最近更新 更多