sed: How to Escape Forward Slash with the Right Delimiter
/* Posted November 11th, 2008 at 10:02am *//* Filed under How-To, Linux */
/* */

If you’ve used Linux at all, you may have come across ’sed,’ short for "stream editor," which is a powerful little utility to modify streams like console IO, files or text. I was using it recently to do a simple search and replace operation in a few files. However, a curious problem arose that I had not encountered before. I’ve used ’sed’ many a time to perform a find and replace on text within a file, but I’d never included the slash ‘/’ (also known as "forward slash") character in my search text with sed. As you may know, sed can easily perform a search and replace on all *.txt files in a directory with this command:
% sed s/text_to_replace/replacement_text/g *.txt
Note how forward slash "/" is used as part of the regular expression to separate the command options and search text. Naturally, since I had text that I wanted to replace with forward slash characters, my sed command contained escaped slash characters and looked like this:
% sed s/file:\/\//http:\/\//g *.txt
I wanted to replace "file://" with "http://" text so in order not to confuse the delimiter with the text, I escaped the forward slashes with backslashes like so \/. Unfortunately, sed didn’t like what I gave it and gave and output like:
sed: -e expression #1, char 10: unknown option to `s'
No matter how I escaped the forward slash or how many other characters I escaped with backslash, sed simply would not do what I wanted it to do. Then I discovered quite an exciting little tidbit about sed. In the regular expression, it’s not necessary to delimit the find and replace texts and search options with the slash ‘/’ character. In fact, you can use just about any character to delimit the expression:
% sed s#file:\/\/#http:\/\/#g *.txt Using #, @, and A as the delimiter will all work out to the same valid sed operation to find all strings of "file://" text and replace it with "http://" text.
% sed s@file:\/\/@http:\/\/@g *.txt
% sed sAfile:\/\/Ahttp:\/\/Ag *.txt
Image/Flickr/Biappi

















Incidentally sed works a bit differently in a tclsh shell (incase it is used as part of a tcl script)
The following code works! No need to use use backslash.
exec echo $abc | sed “s,file://,http://,g”
Excellent post! This really helped me out a lot. I would have never thought of changes the delimiters!
I managed to escape slashes and then use my new escaped VAR in another sed expr:
ESCAPED_VAR = echo “$SITE_PATH” | sed ’s/\//\\\//g’
(append new line after some_string)
sed “/^some_string /a\ $ESCAPED_VAR” file_old > file_new
Thx
Please delete my previous post. This one works:
$ escape_slash=/fileserver/sn-cvsroot/batchpltf/
$ escape_slash_b=`echo $escape_slash | sed s,/,\\\\\\\\\\/,g`
$ echo $escape_slash_b
\/fileserver\/sn-cvsroot\/batchpltf\/