1

I want to replace, and old string with a new one. This is what I used

sed -i "0,|$old|{s|$old|$new|g}" file

but it gives me error:

sed: -e expression #1, char 3: unexpected `,'

How to change it?

Also

How to change only the last occurence?

example

Apple / Banana / Apple / orange / Apple
                                    |
                                    |
                                   \-/
Apple / Banana / Apple / orange / Melon
  • The later part of your question (about replacing the last occurrence) is much different imho and should be asked as a separate question - and perhaps better asked on the Unix & Linux site. – steeldriver Jan 12 '15 at 23:26
2

With the exception of the substitute (s) command, you need to preface an alternate delimiter with a backslash i.e. to use | as a regex delimiter in your range it has to be 0,\|$old|

So

sed -i "0,\|$old|{s|$old|$new|g}" file

should work (although the brackets around the substitute expression are unnecessary, since it is a single expression).

Note that including the g (global) flag will cause sed to replace all instances of $old within the first matching line:

$ echo -e "old and bold\nolder and bolder\noldest and boldest" | sed "0,\|old| s|old|new|g"
new and bnew
older and bolder
oldest and boldest

If you want to replace the very first instance only, remove the g i.e.

$ echo -e "old and bold\nolder and bolder\noldest and boldest" | sed "0,\|old| s|old|new|"
new and bold
older and bolder
oldest and boldest
  • just remove it or remove |g? – xyz Jan 12 '15 at 19:54
  • I was going to mention the g but assumed that the OP knows what they want (i.e. to replace all instances of $old within the first matching line) – steeldriver Jan 12 '15 at 20:00
0

This should work for you:

sed -i "0,/${old}/s,${old},${new}," file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.