I'm trying to replace some text in a file as described in title. What i tried:
newdir=/dir/to/my/file
sed -i "s/'MyDir'/${newdir}/g" myconf.conf
The command above gives this error:
unknown option to `s'
The problem is that $newdir
contains /
characters, so your sed
command ends up looking like s/'MyDir'//dir/to/my/file/g
, which won't work -- the first /
effectively terminates your sed
expression, and everything else is garbage.
Fortunately, sed
let's you use any character as a delimiter to the s
command, so you could write instead:
sed -i "s|'MyDir'|${newdir}|g" myconf.conf
One way to get around the "does my data contain the delimiter" problem is to use shell variable expansion to escape the delimiter character:
sed -i "s|'MyDir'|${newdir//|/\\|}|g" myconf.conf
Demo:
$ newdir="/a/dir/with|a/pipe"
$ sed "s|'MyDir'|${newdir}|g" <<< "this is 'MyDir' here"
sed: 1: "s|'MyDir'|/a/dir/with|a ...": bad flag in substitute command: 'a'
$ sed "s|'MyDir'|${newdir//|/\\|}|g" <<< "this is 'MyDir' here"
this is /a/dir/with|a/pipe here
You can do this with the default slash delimiter, with more escapes
sed -i "s/'MyDir'/${newdir//\//\\\/}/g" myconf.conf