0

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)?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255

2 Answers2

2

Use .*:

grep "${word1}.*${word2}" "$filename"
  • . matches any character
  • * matches any number of the preceding character
pLumo
  • 22,565
0

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.

Kusalananda
  • 333,661