1

This page says that any multiplier in a regex can be suffixed with '?' to do a non greedy search. However, I can't figure out how to make it work in grep.

grep -E '^.*?$' file

prints the whole text.

How can I do a non greedy regex search with grep?

ilkkachu
  • 138,973
saga
  • 1,401
  • In any case, ^.*?$ will match the same thing as ^.*$ as that's constrained by the ^ and $. Non greedy operators are not useful for grep (that print the matching lines, unless you use non-standard extensions like GNU's -o) as they don't affect which lines do match the pattern, just what is being matched inside the line. – Stéphane Chazelas May 28 '17 at 06:49
  • Though grep -o is somewhat common even if nonstandard, and a non-greedy match might come useful there. – ilkkachu May 28 '17 at 08:42
  • 2
    That page you link to seems to describe Perl regexes the whole time, but doesn't explicitly say that, and worse, doesn't even mention that there are different variants of REs. See also this question about the different types of regexes. – ilkkachu May 28 '17 at 08:47

1 Answers1

2

You need grep with PCRE (Perl Compatible Regular Expression) support. e.g. GNU grep has this -- can be leveraged with the -P option. There is also a standalone program named pcregrep that can be installed on many systems with regular packaging.

Note that, -E enables ERE (Extended Regular Expression) that does not have non-greedy matching support with the ? token.

So, with GNU grep you can do e.g.:

grep -Po '^.*?foo' file

to match (and extract) upto first foo from start.

heemayl
  • 56,300