首页 > 解决方案 > 在文本文件列表中同时搜索多个模式

问题描述

我有一个包含文本文件的文件夹,并且想在所有文本文件中搜索,如果它们同时有某些单词,不一定在同一行。我已经尝试过,grep但逐行工作:

file-1.txt

You shall find of the king a husband, madam; you,
sir, a father: he that so generally is at all times
good must of necessity hold his virtue to you; whose
worthiness would stir it up where it wanted rather
than lack it where there is such abundance.

file-2.txt

He was excellent necessity, madam: the father very
lately spoke of him admiringly and mourningly: he
was skilful enough to have lived still, if knowledge
could be set up against mortality.
He hath abandoned his physicians, king; under whose
practises he hath persecuted time with hope, and
finds no other advantage in the process but only the
losing of hope by time.

我想检测kingfather是否存在于同一个文件中。我试过的代码是:

for file in file-*.txt; do grep -E 'king.*father' "$file" && echo $file; done

但没有运气。有什么帮助吗?

标签: text

解决方案


你在这里有两个问题:

A) grep -E 仍然无法跨行工作。使用 -z 会有所帮助,使所有文件都计为一行:

for file in file-*.txt; do grep -z  'king.*father' "$file" && echo $file; done
  • 这将匹配 file-1.txt

B)我明白你也需要不同顺序的单词吗?为此,您需要 egrep,并在 () 中指定两个表达式,用 | 分隔:

for file in file-*.txt; do egrep -z  '(king.*father|father.*king)' "$file" && echo $file; done

推荐阅读