How to do a non-greedy match in grep?

syker picture syker · Jun 12, 2010 · Viewed 125.8k times · Source

I want to grep the shortest match and the pattern should be something like:

<car ... model=BMW ...>
...
...
...
</car>

... means any character and the input is multiple lines.

Answer

Mark Byers picture Mark Byers · Jun 12, 2010

You're looking for a non-greedy (or lazy) match. To get a non-greedy match in regular expressions you need to use the modifier ? after the quantifier. For example you can change .* to .*?.

By default grep doesn't support non-greedy modifiers, but you can use grep -P to use the Perl syntax.