На этот вопрос уже есть ответ здесь:
Как мы можем использовать 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.
Простой способ со множественными вызовами 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.
Можно использовать предвидения с 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"