Sed - How to escape variable number of "/" (slash) ?

Hi,

Can you tell me how to escape a variable number of slash characters in sed "/" ?

In the script the code looks like this:

cat $file_to_update | sed s/^$param/$param=$tab2*\#\*/1

And the $tab2 value is a path so it will have a number of "/" charracters.

# cat db.cfg | sed "s/^OutputDirectory/OutputDirectory=/var/opt/*#*/1"
sed: command garbled: s/^OutputDirectory/OutputDirectory=/var/opt*#*/1
 And also "\" does not seem to work:
# cat db.cfg | sed s/^OutputDirectory/OutputDirectory=\/var\/opt*#*/1
sed: command garbled: s/^OutputDirectory/OutputDirectory=/var/opt*#*/1

The best way to deal with paths in sed is to use a character other than / as the regexp delimeter --any will do, i.e.

sed s,a,b,

is just the same as

sed s/a/b/

Then you don't have to escape the slashes in the search/replace patterns.

Either you do like spirtle said or you use a separate sed script to change every "/" in the $tab2 variable to a "\/" prior to using the variables content:

tab2="(print - "$tab2" | sed 's/\//\\\//g')"

I hope this helps.

bakunin

Thank you spirtle it works with the comma.

Do you now how to properly escape backslash too?

I need to replace every "/" from a variable with "\\/" but this does not seem to work if I put it in a variable. Here is an example:

[root@europa:/]# echo $escape_slash
/fileserver/sn-cvsroot/batchpltf/
[root:/]# echo $escape_slash | sed s,/,\\\\\\\\\\/,g
\\/fileserver\\/sn-cvsroot\\/batchpltf\\/

As you can see instead of "\\" I always get a single "\" in the variable no matter how many "\" characters I place in there:

[root:/]# escape_slash_b=`echo $escape_slash | sed s,/,\\\\\\\\\\/,g`
[root@europa:/]#  echo $escape_slash_b
\/fileserver\/sn-cvsroot\/batchpltf\/

If I replace "/" with only "\/" sed gives an error on my system so I noticed that "\\/" works(but not from a variable tho, which is what I need).

majormark, you missed the point of spirtle's post. If you use:
sed "s/old/new/"
then slash becomes a special character and you must escape any slashes that appear in either the old or new strings. But switch to:
sed "s=old=new="
and now slash is just another character that need not be escaped. so change that delimiter character to something that is not used in either the old or new strings. Then forget about the backslashes.