Search code examples
regexshellcommand-linegrepregex-greedy

How to do a non-greedy match in grep?


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.


Solution

  • 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.