1820475 Members
2971 Online
109624 Solutions
New Discussion юеВ

Backslash in SED

 
SOLVED
Go to solution
FRED Dennison
Advisor

Backslash in SED

I am trying to use SED to alter a variable with forward slashes in it (an omniback session reference "2000/12/31-5"). The aim is to use this variable in another SED statement to subtitute it for another String, but the forward slahes cause problems. I was intending to program in backslashes before each forward slash in the variable, then use the result to replace the relevant strings.

Command 1 = export $SESSION = echo 2000/12/31-5 | sed -e "s/\//\/g" # (Replace / with \/ - doesn't work)

Command 2 = sed -e "s/var1/$SESSION/g" # ($SESSION = result of Command1)

Any ideas?
Peace thru superior firepower.
6 REPLIES 6
Curtis Larson
Trusted Contributor
Solution

Re: Backslash in SED

it should be :
sed -e 's/\//\\\/g'

or you can use another delimiter:

sed -d 's|/|\\/|g'
Curtis Larson
Trusted Contributor

Re: Backslash in SED

oops that should have been a -e instead of -d:

and, of course, if you use a different delimiter you don't need to backslash your slashes in the substitution
James R. Ferguson
Acclaimed Contributor

Re: Backslash in SED

Fred:

Try:

# echo 2000/12/31-5 | sed -e "s?/?\\\?g"

...JRF...

FRED Dennison
Advisor

Re: Backslash in SED

Thanks for your assistance. It's works OK now.

Interesting point; the answers above gives the result I wanted to stdout, but to store it in a variable, I had to put another 3 \ characters in the sed command. End result was

export S2='echo $S1|sed -e "s?/?\\\\\\\/?g"'

with ? as delimeter.

FRED
Peace thru superior firepower.
Dan Hetzel
Honored Contributor

Re: Backslash in SED

Hi Fred,

The reason why you have to add a couple backslashes when assigning the result to a variable is the following:
Using double quotes doesn't prevent your shell from interpreting the string, you should use simple quotes instead, like in:
a=`echo 2000/12/31-5 | sed -e 's#/#\\\#g'`

This keeps the whole expression 'more readable'. ;-)

Best regards,

Dan
Everybody knows at least one thing worth sharing -- mailto:dan.hetzel@wildcroft.com
Ian_9
New Member

Re: Backslash in SED

sed uses ed and that states that "s/whatever/something/" can be "s;whatever;something;". IE the "/" is an ed delimiter. Using anything other than "/" usually gets rid of the problems you are having.

Regards
ian