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?

  • 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 6:49
  • Though grep -o is somewhat common even if nonstandard, and a non-greedy match might come useful there. – ilkkachu May 28 '17 at 8: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 8:47

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.

  • grep -Po '^.*?$' file also prints the full contents of file. – saga May 28 '17 at 4:12
  • @saga With ^.*?$, you are matching from start (^) to end ($), thats why...whats your plan? – heemayl May 28 '17 at 4:13
  • I got it, grep does a line wise search, thanks for help. – saga May 28 '17 at 4:17

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.