【问题标题】:Join files based on two columns using awk使用 awk 基于两列连接文件
【发布时间】:2018-07-15 03:03:06
【问题描述】:

我有以下两个文件;

$ cat file1
1 4
2 5
3 6

$ cat file2
4 2 N1
4 1 Y1
6 2 N2
6 3 Y2
2 5 Y3

我对@9​​87654325@的第三栏感兴趣。所以我想加入基于两个第一列的两个文件,它们是 ID 列。经过大量搜索(例如hereherehere),我尝试了一些方法,它原则上有效;

awk 'FNR==NR{a[$1,$2];next}; ($1, $2) in a || ($2, $1) in a{print $3}' file1 file2
Y1
Y2
Y3

或者,

awk 'FNR==NR{a[$1,$2]=$3;next}; ($1, $2) in a || ($2, $1) in a{print $0, a[$1,$2]}' file2 file1
1 4
2 5 Y3
3 6

但不是我想要的确切输出;

1 4 Y1
2 5 Y3
3 6 Y2

file1 中 ID 的顺序很重要,因为第一列是男性,第二列是女性。在file2 中,这些列可能是男性也可能是女性。

【问题讨论】:

    标签: unix awk text-processing


    【解决方案1】:

    像这样:

    awk 'NR==FNR{s[$1 OFS $2]; next}
         ($2 OFS $1) in s {
             print $2, $1, $3
         }
         ($1 OFS $2) in s {
             print $1, $2, $3
         }' file file2
    

    【讨论】:

    • 更好!不准确,因为我需要与 file1 中相同的列。查看所需的输出..
    • 您的回答启发了我自己的解决方案,awk 'NR==FNR{s[$1 OFS $2]=$3; next}($2 OFS $1) in s || ($1 OFS $2) in s{if(s[$1 OFS $2]=="") print $0,s[$2 OFS $1]; else print $0,s[$1 OFS $2]}' file2 file1
    • 好的,我也改了答案。
    • 太棒了:),比我的版本好
    • 不错。很高兴看到它有所帮助。 :)
    【解决方案2】:

    不是很短,但可以:

    $ awk 'FNR==NR{a[$1,$2]=$1 FS $2;a[$2,$1]=a[$1,$2];next}; ($1,$2) in a || ($2,$1) in a{print a[$1,$2],$3}' file1 file2
    
    1 4 Y1
    3 6 Y2
    2 5 Y3
    

    替代方案:

    $ awk 'FNR==NR{a[$1,$2]=$1 FS $2;next}; {pr=0};($1,$2) in a {pr=a[$1,$2]};($2,$1) in a{pr=a[$2,$1]};pr{print pr,$3}' file1 file2
    

    【讨论】:

    • 很好,谢谢!正如您回答的那样,我偶然发现了一个受@hek2mgl 启发的解决方案; awk 'NR==FNR{s[$1 OFS $2]=$3; next}($2 OFS $1) in s || ($1 OFS $2) in s{if(s[$1 OFS $2]=="") print $0,s[$2 OFS $1]; else print $0,s[$1 OFS $2]}' file2 file1.
    猜你喜欢
    • 2015-12-20
    • 1970-01-01
    • 2015-11-07
    • 2012-10-26
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-16
    相关资源
    最近更新 更多