【问题标题】:Compare two text files with two columns, find matches in first column, output match to third file比较两个包含两列的文本文件,在第一列中找到匹配项,将匹配项输出到第三个文件
【发布时间】:2015-07-13 07:58:02
【问题描述】:

我有两个文本文件。

file1.txt

AAA example1
BBB example2
CCC example3
DDD example4

file2.txt

FFF example5
AAA example1
BBB example2
GGG example6

我想比较两个文件的第一列,如果匹配,则输出从file1.txtfile3.txt 的整行,如下所示:

file3.txt

AAA example1
BBB example2

【问题讨论】:

    标签: regex awk


    【解决方案1】:

    查找第二个文件的第一列到第一个文件的第一列的所有匹配项,打印第一个文件的两列匹配项,然后将其添加到file3.txt

    awk 'NR==FNR{a[$1];next}$1 in a' file2.txt file1.txt >> file3.txt
    

    解释:

    NRFNR 内置在 awk 变量中,表示输入记录的总数和当前文件中的记录数。

    NR==FNR # when in the first file (file2)
    {
        a[$1] # build associative array on the first column of file2
        next  # process next line
    }
    ($1 in a) # if value in first column of the second file (file1) is in the array, get the whole line
    

    >> file3.txt 通过管道将 awk 打印的内容发送到 file3。

    【讨论】:

    • 您不需要打印部分,应该这样做:awk 'NR==FNR{a[$1];next} $1 in a' file1 file2
    • 谢谢,已更新。如果您想抓取特定列,打印部分很有用,否则如果您抓取整行,则不需要它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多