This question already has an answer here:

I want to look for lines with "word1 ... word2" where '...' could be any different characters. So far I have used two greps for the same like this:

grep "$word1" $filename | grep "$word2"

Is there a faster way to do this by suppose something like this:

grep "$word1*$word2" $filename

where maybe * could be some special character which can be any other character(s)?

marked as duplicate by Jeff Schaller, schily, slm Jun 22 '18 at 1:11

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


Use .*:

grep "${word1}.*${word2}" "$filename"
  • . matches any character
  • * matches any number of the preceding character
  • 2
    More precisely, .* matches any chararacter repeated 0 or more times (IOW, it matches any string, including the empty string). – NickD Jun 21 '18 at 11:50
  • This is precisely what I was looking for – Pratik Mayekar Jun 21 '18 at 11:52

If you need the two words to be delimited, i.e. if you do not want to match abba if one of the words is bb, then use

grep "\\<$word1\\>.*\\<$word2\\>" "$filename"

The pattern \< (here \\< to escape the first backslash from the shell) matches just before a word, and \> works similarly but just after a word.

There's alo \b that matches either before and after, and [[:<:]] and [[:>:]] that work just like \< and \>. Which ones that are implemented by grep varies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.