将一列与另一个文件unix的另一列匹配

时间:2019-07-09 14:13:17

标签: unix join awk grep pattern-matching

我有file_1

BlockID
VT11742
VT11744
VT11050
VT11870
VT12147
VT12149
VT12176
VT12180

和file_2

AB Ref2        VICTOR 
crc_31-C1        VT11929
crc_31-C2     VT11929 C2
crc_31-N VT11929 NORMAL
crc_32-C1        VT11050
crc_32-C2     VT11050 C2
crc_33-C1        VT11656
crc_33-C2     VT11656 C2
crc_33-N VT11656 NORMAL
crc_34-C1        VT11981
crc_34-C2     VT11981 C2

我想要的输出是在文件1的第一列与文件2匹配时打印出文件2的第一列,并以与文件2相同的顺序打印,在没有匹配项时打印

输出

BlockID
VT11742 no_match
VT11744 no_match
VT11050 crc_32-C1
VT11870 no_match
VT12147 no_match
VT12149 no_match
VT12176 no_match
VT12180 no_match

我以为我可以做这样的事情 grep -Ff file1 file2>输出

3 个答案:

答案 0 :(得分:4)

请您尝试以下操作(用显示的示例编写并测试)。

BlockID
VT11742 no_match
VT11744 no_match
VT11050 crc_32-C2
VT11870 no_match
VT12147 no_match
VT12149 no_match
VT12176 no_match
VT12180 no_match

输出如下。

{{1}}

答案 1 :(得分:0)

print out in the same order of file2,您要(但在您的示例中未显示):

$ awk 'NR==FNR{if (NR==1) print; else a[$1]; next} FNR>1{print $2, ($2 in a ? $1 : "no_match")}' file1 file2
BlockID
VT11929 no_match
VT11929 no_match
VT11929 no_match
VT11050 crc_32-C1
VT11050 crc_32-C2
VT11656 no_match
VT11656 no_match
VT11656 no_match
VT11981 no_match
VT11981 no_match

答案 2 :(得分:0)

这是另一个awk脚本。对于不清楚的要求。希望它对您有用。

script.awk

FNR == NR { # process file 1 only
    keysArr[$2] = $1; # read each 2nd field into array
    next;   # skip any further handling
}
FNR > 1{    # process file 2 form line 2
    $2 = "no match";   # set default match result
    if ($1 in keysArr) { # match key in file 1
         $2 = keysArr[$1]; # overwrite 2nd output field
    }
}
1           # ouput everything computed for file 2

input.1.txt

BlockID
VT11742
VT11744
VT11050
VT11870
VT12147
VT12149
VT12176
VT12180

input.2.txt

AB Ref2        VICTOR
crc_31-C1        VT11929
crc_31-C2     VT11929 C2
crc_31-N VT11929 NORMAL
crc_32-C1        VT11050
crc_32-C2     VT11050 C2
crc_33-C1        VT11656
crc_33-C2     VT11656 C2
crc_33-N VT11656 NORMAL
crc_34-C1        VT11981
crc_34-C2     VT11981 C2

运行:

awk -f script.awk input.2.txt input.1.txt

输出:

BlockID
VT11742 no match
VT11744 no match
VT11050 crc_32-C2
VT11870 no match
VT12147 no match
VT12149 no match
VT12176 no match
VT12180 no match
相关问题