Non greedy pattern match in sed

Kim Holburn kim.holburn at
Tue Aug 13 21:15:06 EST 2002

At 4:25 PM +1000 2002/08/13, Michael Still wrote:
>I would like non greedy regexp matching in sed.
>echo "/* This is a */ test /* line */" | sed 's/\/\*.*\*\//g'
>                                                            ^^
>                                                    Non greedy toggle
>                                                    here?
>Should result in:
>" test "
>Any hints?

If you use perl you can do this. From the perl manual (man perlre)

       By default, a quantified subpattern is "greedy", that is,
       it will match as many times as possible (given a particu-
       lar starting location) while still allowing the rest of
       the pattern to match.  If you want it to match the minimum
       number of times possible, follow the quantifier with a
       "?".  Note that the meanings don't change, just the

           *?     Match 0 or more times
           +?     Match 1 or more times
           ??     Match 0 or 1 time
           {n}?   Match exactly n times
           {n,}?  Match at least n times
           {n,m}? Match at least n but not more than m times

 .... | perl -p -e 's/\/\*.*?\*\//g'

> echo "/* This is a */ test /* line */" |perl -p -e 's/\/\*.*?\*\///g'

>Michael Still (mikal at     UMT+10hrs

Kim Holburn  Network Consultant  P: +61 2 61258620 M: +61 0417820641
Email: kim.holburn at - PGP Public Key on request

Life is complex - It has real and imaginary parts.
     Andrea Leistra (rec.arts.sf.written.Robert-jordan)

More information about the linux mailing list