Non greedy pattern match in sed
Kim Holburn
kim.holburn at anu.edu.au
Tue Aug 13 21:15:06 EST 2002
At 4:25 PM +1000 2002/08/13, Michael Still wrote:
>Hey,
>
>I would like non greedy regexp matching in sed.
>
>i.e.
>
>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
"greediness":
*? 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'
test
>
>Thanks,
>Mikal
>
>--
>
>Michael Still (mikal at stillhq.com) UMT+10hrs
--
--
Kim Holburn Network Consultant P: +61 2 61258620 M: +61 0417820641
Email: kim.holburn at anu.edu.au - 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