Sunday, April 28, 2024
4
rated 0 times [  4] [ 0]  / answers: 1 / hits: 2812  / 2 Years ago, fri, november 4, 2022, 8:33:06

How can we use grep to get line(s) containing a group of words, while the order of words is not important, although line(s) should contain all words mentioned in search?



I have done that with phasing the search (with piping, saving the outputs in temporary files, and searching again), but I'd like to know if I can do that in one attempt.



Here is a sample; I want to search in the lines below for lines containing sample, words, list:



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.


And get this result:



it's a sample test file for a list of words.
list of words without a specific order, it's a sample.

More From » command-line

 Answers
3

The easy way is with multiple calls to grep:



grep sample testfile.txt | grep words | grep list


A demonstration:



echo -e "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.
something 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.

[#7366] Friday, November 4, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
assionortly

Total Points: 423
Total Questions: 121
Total Answers: 115

Location: Chad
Member since Wed, Sep 30, 2020
4 Years ago
;