我们如何使用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"
(通过)