【问题标题】:AWK print line from File A if string in 2 columns are both present in File B如果 2 列中的字符串都存在于文件 B 中,则 AWK 打印文件 A 中的行
【发布时间】:2020-06-11 00:34:59
【问题描述】:

我正在尝试提取 FileB 中存在的来自 FileA 的 Col1 和 Col2 的行。

例如,

文件A:

1000963 4852419 0.051 0.0103 0.1126
1001037 1957033 0.044 0.0154 0.0473
1001107 1690854 0.045 0.0145 0.0612
1001176 1996721 0.067 0 0.2494

文件B:

1281525
1000963
1690854
1001176
1001037
1957033
1996721
5784681

在上面的例子中,我希望输出是:

1001037 1957033 0.044 0.0154 0.0473
1001176 1996721 0.067 0 0.2494

请注意,其他两行没有被拉出,因为 FileB 中只有一列(不是两列)中的字符串。

有没有办法在 awk 中做到这一点?到目前为止,我的尝试都没有奏效。

谢谢!

【问题讨论】:

    标签: awk


    【解决方案1】:

    请您尝试关注一下。

    awk 'FNR==NR{a[$0];next}  (($1 in a) && ($2 in a))' Input_file2  Input_file1
    

    说明:为上面添加详细说明。

    awk '                          ##Starting awk program from here.
    FNR==NR{                       ##Checking condition if FNR==NR which will be TRUE when Input_file2 is being read.
      a[$0]                        ##Creating array a with index $0 here.
      next                         ##next will skip all further statements from here.
    }
    (($1 in a) && ($2 in a))       ##Checking if current line 1st and 2nd  field both are present in array then print current line.
    ' Input_file2  Input_file1     ##Mentioning Input_file names here.
    

    【讨论】:

    • 将添加简短的解释来回答。
    • @RavinderSingh13 谢谢 - 这比我尝试做的方式简单得多!谢谢 - 它有效:)
    • @LauraC:没有必要删除您的问题,而且在有人投入时间和精力并发布答案之后也是不公平的。
    • @anubhava 我最终决定不删除它,因为来自另一个用户的 cmets 已被删除。如果您看过多个 cmets,您就会明白我为什么要考虑删除。我将保留它,因为我很感激这个答案,并希望它会帮助其他人寻找类似的答案:)
    • @LauraC 感谢您的评论,我相信您的立场是正确的。
    猜你喜欢
    • 1970-01-01
    • 2013-06-03
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多