Tuesday, February 22, 2011

sed: How to Escape Forward Slash

As you may know, sed performs a search and replace with this command:

sed s/seacrh pattern/replacement pattern/g file list

forward slash ("/") is used as part of the regular expression to separate the command options and search text. What if your search/replace pattern itself includes forward slash character.

I wanted to replace /usr/local/bin to /usr/local/dev, I escaped forward slashes with backward slash and my sed command looked like this:

sed -i -e 's/\/usr\/local\/bin/\/usr\/local\/dev/g' testfile.txt

Unfortunately, sed didn’t work and gave me this error:

sed: -e expression #1, char 27: unknown option to `s'

Then On googling, I discovered an exciting thing about sed. In the regular expression, it’s not necessary to delimit the find and replace texts and search options with the forward slash ‘/’ character. We can use any character to delimit the expression.

So I changed my command a bit, used @ character to delimit the expression and then it worked.

sed -i -e s@\/usr\/local\/bin@\/usr\/local\/dev@g testfile.txt

1 comment:

Jason Harris said...

Brilliant, thanks. I tried it in the tar -s option and it works there too:

tar -cf newTarFile.tar -s @.*@new-prefix/~@g *

So using @ as the separator (instead of a /) means that / can be used as a replacement char in the match.

tar -cf newTarFile.tar -s /.*/new-prefix/~/g * results in a 'Invalid replacement flag' error no matter how you try to escape the forward-slash.