the_eraser
the_eraser

Reputation: 425

Regex to match as few many times as possible (lazy) using grep

I'm quite new to regex. I have the following simple line in a txt file.

This one has some different PATTERNs, including PTTRN, and PTN, then it repeats PTTRN and PATTERN

Using grep -E, I want to match everything between the first PATTERN and the first PTTRN without extending the match to the second PTTRN.

I tried doing

PATTERN.*?PTTRN

That seems to work in https://regex101.com/r/qI4aA6/8

But when I try using it in the terminal with grep, it colours all the way down to the second PTTRN, that is

PATTERNs, including PTTRN, and PTN, then it repeats PTTRN

Besides, I'm using the default grep (gnu grep) on my ubuntu system.

Upvotes: 2

Views: 426

Answers (1)

anubhava
anubhava

Reputation: 785058

You can use -P (PCRE) flag with gnu-grep:

grep -oP 'PATTERN.*?PTTRN' file
PATTERNs, including PTTRN

Or else on BSD grep:

grep -oE 'PATTERN.*?PTTRN' file
PATTERNs, including PTTRN

Upvotes: 2

Related Questions