【问题标题】:how extract exact match from a file without grep -w如何在没有 grep -w 的情况下从文件中提取完全匹配
【发布时间】:2015-04-15 08:26:53
【问题描述】:

我有一个文件 A,其中有一列,其中包含如下字符串列表:

12
123
1234
1234567

我想使用文件A中的字符串来grep文件B中包含它们的行,文件B看起来像这样:

1       0/0     ./.     0/1     0/0
12      0/0     0/0     1/1     ./.
1234    1/1     0/1     ./.     0/0
12345   0/0     0/0     1/1     1/1
123456  1/1     1/1     ./.     ./.

在这种情况下,我正在等待与文件 A 中的字符串完全匹配的输出,如下所示:

12      0/0     0/0     1/1     ./.
1234    1/1     0/1     ./.     0/0

我使用了grep -wf A B,它运行良好,但问题是我的真实文件非常重,而且处理成本非常高。有人有任何不同的想法来获得相同的结果,但使用其他命令行?

【问题讨论】:

  • grep -wFf A B 跑得更快吗? (我怀疑这可能是因为它使用固定字符串而不是正则表达式匹配)
  • 是的!它跑得更快!两个答案都OK,非常感谢!!

标签: bash shell grep exact-match


【解决方案1】:

您可以使用这个 awk 作为替代:

awk 'NR==FNR{a[$1]; next} $1 in a' file1 file2
12      0/0     0/0     1/1     ./.
1234    1/1     0/1     ./.     0/0

说明:

NR == FNR {                  # While processing the first file
  a[$1]                      # store the 1st field in array a
  next                       # move to next line
}
$1 in a                      # while processing the second file
                             # if 1st field is in array then print it

【讨论】:

    猜你喜欢
    • 2017-12-31
    • 2021-01-16
    • 2016-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    • 2014-03-08
    相关资源
    最近更新 更多