【问题标题】:awk search column from one file, if match print columns from both files来自一个文件的 awk 搜索列,如果匹配来自两个文件的打印列
【发布时间】:2015-09-19 00:51:05
【问题描述】:

我正在尝试比较 file1 中的第 1 列和文件 2 中的第 3 列,如果它们匹配,则打印 file1 中的第一列和 file2 中的前两列。

以下是每个文件的示例:

文件1

Cre01.g000100   
Cre01.g000500  
Cre01.g000650  

文件2

chromosome_1    71569  |655|Cre01.g000500|protein_coding|CODING|PAC:26902937|1|1)
chromosome_1    93952  |765|Cre01.g000650|protein_coding|CODING|PAC:26903448|11|1)
chromosome_1    99034  |1027|Cre01.g000100 |protein_coding|CODING|PAC:26903318|9|1)

想要的输出

Cre01.g000100  chromosome_1    99034        
Cre01.g000500  chromosome_1    71569   
Cre01.g000650  chromosome_1    93952

我一直在查看一些有点相似的各种线程,但我似乎无法让它打印两个文件中的列。以下是一些相关的链接:

awk compare 2 files, 2 fields different order in the file, print or merge match and non match lines

Obtain patterns from a file, compare to a column of another file, print matching lines, using awk

awk compare columns from two files, impute values of another column

Obtain patterns in one file from another using ack or awk or better way than grep?

Awk - combine the data from 2 files and print to 3rd file if keys matched

我觉得我应该能够根据这些线程弄清楚它,但是这两天我一直在尝试不同的代码变体,但我没有得到任何结果。 这是我尝试在我的文件上使用的一些代码:

awk 'FNR==NR{a[$3]=$1;next;}{print $0 ($3 in a ? a[$3]:"NA")}' file1 file2

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

awk 'FNR==NR{a[$1]=$0; next}{print a[$1] $0}' file1 file2

我知道我必须创建一个临时矩阵,其中包含 file1 的第一列(或 file2 的第三列),然后将其与另一个文件进行比较。如果匹配,则打印文件 1 中的第一列和文件 2 中的第 1 列和第 2 列。

感谢您的帮助!

【问题讨论】:

    标签: regex awk compare match multiple-columns


    【解决方案1】:

    你可以使用这个awk:

    awk -F '[| ]+' -v OFS='\t' 'NR==FNR{a[$4]=$1 OFS $2; next}
           $1 in a{print $1, a[$1]}' file2 file1
    Cre01.g000100   chromosome_1    99034
    Cre01.g000500   chromosome_1    71569
    Cre01.g000650   chromosome_1    93952
    

    【讨论】:

      【解决方案2】:

      你在这三个中的中间尝试是最接近的,但是:

      • 您尚未指定字段分隔符为|
      • 您没有分配给a[$1]
      • 您的示例输出与您想要的输出不一致(示例输出显示文件 1 中的第 1 列和文件 2 中的第 1 列;所需的输出据说是文件 1 中的第 1 列和文件 2 中的第 1 列和第 2 列,尽管这解释取决于文件 2 中 $3 的解释,即两个管道符号之间的名称。

        引用创建此答案时的问题:

        ...比较文件 1 中的第 1 列和文件 2 中的第 3 列,如果它们匹配,则打印文件 1 中的第一列和文件 2 中的前两列。

        desired output
        Cre01.g000100  chromosome_1    99034
        Cre01.g000500  chromosome_1    71569
        Cre01.g000650  chromosome_1    93952
        
      • 我们可以观察到,如果文件 2 中的 $3 等于文件 1 中的值,那么将 $3 打印为保存值一样容易。

      所以,解决这个问题:

      awk -F'|' 'NR==FNR { a[$1]=1; next } ($3 in a) { print $3, $1 }' file1 file2
      

      关键变化是分配给a[$1](和-F'|');其余的都是装饰性的,可以根据您的要求进行调整(由于问题自相矛盾,很难给出更好的答案)。

      【讨论】:

        猜你喜欢
        • 2021-10-01
        • 2018-08-08
        • 2016-12-21
        • 2017-08-19
        • 2020-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多