You're viewing a comment by romainc and its responses.

romainc Permalink
May 29, 2012, 18:29

Oneliner 31 is not quite right, it doesn't replace the first occurence of foo but rather the previous one to last.
This is because * is greedy (not stopping on the first possible match).

$ echo "this is foo and foo another foo quux" | sed 's/\(.*\)foo\(.*foo\)/\1bar\2/'
this is foo and bar another foo quux

One way to do actually replace the first match :

$ echo "this is foo and foo  another foo quux" | sed 's/foo\(.*foo\)/bar\1/'
this is bar and foo  another foo quux

A non greedy operator does not seems to exist in GNU sed (but it exists in software with extended regex engine like vi, perl, ... )

Comment Responses

Anirudh Permalink
February 02, 2016, 03:44

>> $ echo "this is foo and foo another foo quux" | sed 's/foo\(.*foo\)/bar\1/'

Umm, what about this?

$ echo "this is foo and foo  another foo quux" | sed -e 's/foo/bar/'

This replaces the first occurrence of "foo" with "bar".

Reply To This Comment

(why do I need your e-mail?)

(Your twitter handle, if you have one.)

Type the word "browser_95": (just to make sure you're a human)

Please preview the comment before submitting to make sure it's OK.