![如何使用 grep 在文本文件中搜索包含列表中所有单词且没有特定顺序的行?](https://linux22.com/image/1159905/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8%20grep%20%E5%9C%A8%E6%96%87%E6%9C%AC%E6%96%87%E4%BB%B6%E4%B8%AD%E6%90%9C%E7%B4%A2%E5%8C%85%E5%90%AB%E5%88%97%E8%A1%A8%E4%B8%AD%E6%89%80%E6%9C%89%E5%8D%95%E8%AF%8D%E4%B8%94%E6%B2%A1%E6%9C%89%E7%89%B9%E5%AE%9A%E9%A1%BA%E5%BA%8F%E7%9A%84%E8%A1%8C%EF%BC%9F.png)
我们如何使用grep
来获取包含一组单词的行,而词序不重要,尽管应该包含所有单词在搜索中提到过吗?
我已经通过分阶段搜索(使用管道、将输出保存在临时文件中并再次搜索)完成了此操作,但我想知道是否可以在一次尝试中完成此操作。
以下是一个示例;我想在下面的行中搜索包含以下内容的行样本,字,列表:
it's a sample test file for a list of words.
list of words without a specific order, it's a sample.
line with no search keyword here.
list the sample files.
something completely different.
并得到这个结果:
it's a sample test file for a list of words.
list of words without a specific order, it's a sample.
答案1
简单的方法是多次调用grep
:
grep sample testfile.txt | grep words | grep list
演示:
echo -e "it's a sample test file for a list of words.\nlist of words without a specific order, it's a sample. \nline with no search keyword here. \nlist the sample words. \nsomething completely different." | grep sample | grep words | grep list
it's a sample test file for a list of words.
list of words without a specific order, it's a sample.
list the sample words.
答案2
您可以将前瞻与 Perl-regex 结合使用 ( -P
):
grep -P '(?=.*list)(?=.*words)(?=.*sample)'
例子:
echo "it's a sample test file for a list of words.
list of words without a specific order, it's a sample.
line with no search keyword here.
list the sample words.
sample line with only two of the keywords inside.
something completely different." \
| grep -P '(?=.*list)(?=.*words)(?=.*sample)'
it's a sample test file for a list of words.
list of words without a specific order, it's a sample.
list the sample words.
(通过)
使用agrep
( sudo apt install agrep
) 你可以链接多个模式:
agrep "sample;words;list"
(通过)