Strange Sed !!

 
wload/lscp/home/lscpvbf > v=1/1/1/
wload/lscp/home/lscpvbf > v=`echo $v|sed -e "s/\//\\\//g"`;echo $v
1/1/1/
wload/lscp/home/lscpvbf > v=1/1/1/
wload/lscp/home/lscpvbf > v=`echo $v|sed -e 's/\//\\\//g'`;echo $v
sed: Function s/\//\\//g cannot be parsed.
wload/lscp/home/lscpvbf > v=1/1/1/
wload/lscp/home/lscpvbf > v=`echo $v|sed -e 's?\/?\\\/?g'`;echo $v
1\/1\/1\/
wload/lscp/home/lscpvbf > uname -a
AIX tide2e16 3 5 00C7810F4C00
wload/lscp/home/lscpvbf >
 

Can some one please let me know the reason behind this strange behaviour of SED?

One extra backslash is there in your script....

see below output..

$ v=1/1/1/
$ echo "$v" | sed 's/\//\\/g'
1\1\1\

I will only breakdown the first example. From that hopefully you'll be able to understand the rest.

There are three levels of parsing in `sed -e "s/\//\\\//g"` which may consider a backslash to be special (for each step, active escape sequences are highlighted in bold red):

1) With the obsolete form of command substitution, `...` , the backslash is special when it is followed by another backslash, dollar, or backtick.
`sed -e "s/\//\\\//g"` ==> sed -e "s/\//\\//g"

2) Now that the shell has processed the text of the subshell's command, it creates the subshell to execute the command. That subshell then processes the double-quoted string. In a double-quoted string, the backslash is also special when it occurs before certain characters, but it's not the same set of characters as when parsing a backtick command substition. In this context, backslash is special when followed by another backslash, a dollar, a double-quote, a backtick, or a newline.
sed -e "s/\//\\//g" ==> sed -e s/\//\//g

3) Finally, we reach sed, which sees an expression that replaces a backslash-escaped regular expression delimiter (forward slash in this case) with the same. This does not yield any change in the text.
s/\//\//g

Regards,
Alister

1 Like

Thanks Alister for the reply....

Does this mean we cant achieve the required result (1/1/1/-->1\/1\/1\/) from SED with backslash as delimeter?

Regards,
Vidya

Here you go...

$ echo $v | sed 's/\//\\\//g'
1\/1\/1\/

I got the output for the same that you have used..

If you want to modify the value of "v", assign the above reult to v..

v=`echo $v | sed 's/\//\\\//g'`

You can achieve it like this:

v=$(echo $v|sed -e 's/\//\\\//g')

or

v=`echo $v|sed -e 's/\\//\\\\\//g'`
1 Like