Re: A very interesting sed question

Re: A very interesting sed question

am 30.01.2008 16:43:21 von PK

lguo.us@gmail.com wrote:

> I apologize for crossing groups posting ...
>
> Here is my interesting sed question:
>
> echo "/usr/bin:/etc:/usr/local/bin:/opt:/opt/bin" | sed "s?/usr.*:??g"
>
> What I wanted to see for sed "s?/usr.*:??g" is to remove any
> directories containing "/usr" from the string. The correct result
> should be like:
>
> /etc:/opt/:/opt/bin
>
> However, the above sed command doesn't do what I wanted, it returns
> the last directory only.
>
> /opt/bin
>
> so apparently the colon (:) in the sed command matches the last one
> in the string, not the first one after the pattern. How do I fix it?

This is because sed does greedy (ie, longest) match. In your case, the
regxp "/usr.*:" matches "/usr/bin:/etc:/usr/local/bin:/opt:", not
just "/usr/bin:". A simple way to do what you want is to use the
regexp "/usr[^:]*" instead (without double quotes, of course).