【问题标题】:awk comparing two files and filling in blank rows with NAawk 比较两个文件并用 NA 填充空白行
【发布时间】:2018-12-13 07:33:36
【问题描述】:

我正在尝试使用来自 awk compare columns from two files, impute values of another column 的类似命令,并查看了与我的类似的各种问题 awk search column from one file, if match print columns from both files , How to import fields in other columns corresponding to one common field in two files with `NA` in all unmatched columns , awk compare 2 files, 2 fields different order in the file, print or merge match and non match lines 使用具有更多字段但我​​无法使其工作的文件。我还阅读了http://theunixshell.blogspot.com/2012/12/i-have-two-files-file-1-contains-3.html 的内容,看看它是否可行,但我仍然遇到问题:

文件 1:

xx NC1 12 13 ! pro

xy NC1 15 17 ! pro

yx NC1 18 20 ! pro

yy NC1 22 28 ! pro

文件 2

xx ds

xy jt

yy wp

想要的输出:

xx NC1 12 13 ! pro ds

xy NC1 15 17 ! pro jt

yx NC1 18 20 ! pro NA

yy NC1 22 28 ! pro wp

我正在使用的代码:

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

所以基本上我的输出给了我一个新列,都是“NA”,这显然不是我想要达到的。

输出:

xx NC1 12 13 ! pro NA

xy NC1 15 17 ! pro NA

yx NC1 18 20 ! pro NA

yy NC1 22 28 ! pro NA

【问题讨论】:

    标签: unix awk


    【解决方案1】:

    你很接近。

    awk 'NR==FNR {a[$1]=$2;next}{print $0, ($1 in a ? a[$1]:"NA")}' f2 f1
    

    您的问题是,您将file2 作为第一个参数,但是,您认为它是file1file2 根本没有 $6

    【讨论】:

    • 成功了,谢谢。你介意向我解释一下每个部分的作用,以便我更好地理解吗?
    • @JuDoe 您在问题中编写了原始代码,我想您了解这些内容。你对哪一部分有问题要理解
    • 我写的几乎看不懂。这是我所理解的,并且能够在网络上找到搜索。使用两个文件时使用 NR==FNR。 a[$1] 正在创建第一个字段的数组?当它说 a[$1]=$2 是否暗示该文件有两列?我读到 next 告诉 awk 不要处理任何进一步的命令并读入下一条记录并重新开始。但老实说,我不明白它在那里试图做什么。 print $0 是否在没有任何内容可显示该字段时起作用?
    • @JuDoe NR==FNR{a[$1]=$2;next} 获取第一个文件(file2),建立一个哈希表(key=1st col, value=2nd col),当文件处理完毕后,轮到第二个文件(file1),它只会被{print $0, ($1 in a ? a[$1]:"NA")}应用检查col1是否已经在哈希表中(名为a),然后打印,否则,打印NA
    猜你喜欢
    • 2018-03-04
    • 2021-01-26
    • 2017-01-31
    • 2017-07-25
    • 2021-02-21
    • 2012-09-05
    • 2016-07-30
    • 2014-02-20
    相关资源
    最近更新 更多