【问题标题】:grep a large list against a large filegrep 针对大文件的大列表
【发布时间】:2013-10-23 05:45:25
【问题描述】:

我目前正在尝试grep 一个大的 id 列表(约 5000 个)与一个更大的 csv 文件(3.000.000 行)。

我想要所有包含 id 文件中的 id 的 csv 行。

我的幼稚做法是:

cat the_ids.txt | while read line
do
  cat huge.csv | grep $line >> output_file
done

但这需要永远!

有没有更有效的方法来解决这个问题?

【问题讨论】:

标签: linux shell unix awk grep


【解决方案1】:

为此使用grep -f:

grep -f the_ids.txt huge.csv > output_file

来自man grep:

-f 文件,--file=文件

从 FILE 中获取模式,每行一个。空文件包含零 模式,因此不匹配。 (-f 由 POSIX 指定。)

如果您提供一些示例输入,也许我们甚至可以进一步改进grep 条件。

测试

$ cat ids
11
23
55
$ cat huge.csv 
hello this is 11 but
nothing else here
and here 23
bye

$ grep -f ids huge.csv 
hello this is 11 but
and here 23

【讨论】:

    【解决方案2】:

    试试

    grep -f the_ids.txt huge.csv
    

    此外,由于您的模式似乎是固定字符串,因此提供 -F 选项可能会加快 grep。

       -F, --fixed-strings
              Interpret PATTERN as a  list  of  fixed  strings,  separated  by
              newlines,  any  of  which is to be matched.  (-F is specified by
              POSIX.)
    

    【讨论】:

      【解决方案3】:

      当filter.txt 大于几千行时,grep -f filter.txt data.txt 变得不守规矩,因此不是这种情况的最佳选择。即使在使用grep -f 时,我们也需要牢记以下几点:

      • 如果需要匹配第二个文件中的整行,请使用-x 选项
      • 如果第一个文件包含字符串而不是模式,则使用 -F
      • 在不使用-x 选项的情况下使用-w 来防止部分匹配

      这篇文章对此主题进行了很好的讨论(grep -f 讨论大文件):

      而且这篇文章谈到了grep -vf:


      总而言之,处理大文件上的grep -f 的最佳方式是:

      匹配整行:

      awk 'FNR==NR {hash[$0]; next} $0 in hash' filter.txt data.txt > matching.txt
      

      匹配第二个文件中的特定字段(在此示例中使用“,”分隔符和字段 2):

      awk -F, 'FNR==NR {hash[$1]; next} $2 in hash' filter.txt data.txt > matching.txt
      

      对于grep -vf:

      匹配整行:

      awk 'FNR==NR {hash[$0]; next} !($0 in hash)' filter.txt data.txt > not_matching.txt
      

      匹配第二个文件中的特定字段(在此示例中使用“,”分隔符和字段 2):

      awk -F, 'FNR==NR {hash[$0]; next} !($2 in hash)' filter.txt data.txt > not_matching.txt
      

      【讨论】:

        【解决方案4】:

        使用ugrep 可以显着提高搜索速度,以匹配大型huge.csv 文件中the_ids.txt 中的字符串:

        ugrep -F -f the_ids.txt huge.csv
        

        这也适用于 GNU grep,但我希望 ugrep 运行速度快几倍。

        【讨论】:

          猜你喜欢
          • 2019-07-22
          • 2017-07-30
          • 2011-12-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-01-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多