I want to find match with surrounding words. I also want it to be fast.

Here's what I've got:

grep -o -P '(\w+ ){0,n}match( \w+){0,m}'

n is number of words before the phrase, m is number of words after the phrase. match is the phrase I'm looking for.

Is there some faster way of doing that?


echo word1 word2 word3 123 word4 word5 word6 | grep -o -P '(\w+ ){0,2}123( \w+){0,2}'

=> word2 word3 123 word4 word5.


(\w+ ) will match a word or part of word. This means that grep will treat every character in every word as a potential start-of-match. In your example, it will consider each of

  • word1
  • ord1
  • rd1
  • d1
  • 1

before moving on to the successful match (starting at word2).

As you are interested in finding whole words, you can prevent all the attempted mid-word matches by including word boundaries in the pattern:

grep -P '\<(\w+ ){0,2}123( \w+){0,2}\>'

Another effect of this is to prevent matching 123 when it appears inside a longer word.

This cut the time by a factor of 100 for me (test case: searching for the word 'me' in Ulysses)

The "Pitfalls" section of http://www.regular-expressions.info/examples.html has some good pointers on what makes regexps slow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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