Leparevilo Leparevilo - 2 years ago 87
Linux Question

sed does not work as expected with variables in script

I have a small script that does some

global
string replacements in various files. This should be done with
sed
so 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 :(

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download