0

I have a small script that does some global string replacements in various files. This should be done with sedso that only the affected lines are changed.

Preparation:

#!/bin/sh
find="Mücke Motorsport"
replace="Mücke Motorsport Racing Team"
file="/Users/meyer/Dropbox/Dev/App Framework iOS/dev/myfile.txt"

This is my problematic line in the script:

sed -i s/"$find"/"$replace"/g "$file"

Does not work (sed: 1: "/Users/meyer/Dropb ...": invalid command code o). Next try:

sed -i 's/'"$find"'/'"$replace"'/g' "$file"

Does not work (sed: 1: "/Users/meyer/Dropb ...": invalid command code o). Next try:

sed -i "s/$find/$replace/g" "$file"

Does not work (sed: 1: "/Users/meyer/Dropb ...": invalid command code o). Next try:

sed -i s/$find/$replace/g "$file"

Does not work (sed: 1: "Motorsport/Mücke": invalid command code M). Because of this error message I tried to escape my variables:

escaped_ find =$(printf '%s\n' "$find" | sed 's:[][\/.^$*]:\\&:g')
escaped_ replace =$(printf '%s\n' "$replace" | sed 's:[\/&]:\\&:g;$!s/$/\\/')

But usage of the replace variables does´t work ... I don´t know how to get this working :(

Oliver Apel
  • 1,808
  • 3
  • 19
  • 31

1 Answers1

6

On the OSX version of sed, the -i option expects an extension argument so your command is actually parsed as the extension argument and the file path is interpreted as the command code.

Try adding the -e argument explicitly
sed -i'' -e 's/old/new/g' file

Yuriy Zhigulskiy
  • 1,382
  • 9
  • 11