dotancohen
dotancohen

Reputation: 31481

Limiting results to ±5 lines

I am using the following regular expression to find instances of foo and bar in the same file which may be on different lines:

$ pcregrep --color -Mi '(foo[\d\D]*bar)?(bar[\d\D]*foo)?' *

How might I limit this to having the words on ±5 lines?

I am familiar with the {0,5} quantifier but I really don't see how to contrive the query. I was thinking about something ugly like so but I cannot seem to contrive it properly:

[\d\D](\n[\d\D]){0,5}

The above returns the following result:

pcregrep: Error in command-line regex at offset 26: nothing to repeat

Upvotes: 2

Views: 124

Answers (2)

devnull
devnull

Reputation: 123518

The following might work for you:

pcregrep -M '(foo.*(.*\n){0,4}.*?bar)?(bar.*(.*\n){0,4}.*?foo)?' filename

This would find lines containing foo and bar within 5 lines of each other.

EDIT: Adding an alternative as per comments:

pcregrep -M '(foo(\n*.*?){0,4}bar)?(bar(\n*.*?){0,4}foo)?' filename

Upvotes: 1

carlpett
carlpett

Reputation: 12583

I don't have pcregrep, but this works on my (pcre-compliant) tests: (foo(?:.*\n){0,5}bar).

Upvotes: 1

Related Questions