sed – Escaping Backslash in sed

quotingsedshell

I am trying to write a sed command to replace a line in a file. The sed replace required the current working directory, which starts making the command a bit messy because of the characters that need to be escaped.

Here is what I have so far:

sed -i "s/^log.*$/log `echo pwd | sed 's/\//\\\//g'`\/redis\/redis.log\/" ./conf/redis.conf

However this give me an error with sed.

I have tried to break it up into easier commands:

user@ubuntu:~/project$pwd | sed 's/\//\\\//g'
\/home\/user\/project

This returns what I want, but when I try to add in command substitution, it fails:

user@ubuntu:~/project$ echo `pwd | sed 's/\//\\\//g'`
sed: -e expression #1, char 9: unknown option to `s'

Any help would be appreciated

Best Answer

If I'm reading that right, you're trying to replace forward slashes (/) with an escaped forward slash (\/)? This gets a lot easier to handle if you don't use / as your delimiter in sed:

~ $ pwd | sed 's_/_\\/_g'`
\/home\/username
~ $ echo "$( pwd | sed 's_/_\\/_g' )"
\/home\/username
Related Question