Languages and Scripting

Using SED with backslashes in string

 
SOLVED
Go to solution
Theresa Patrie
Regular Advisor

Using SED with backslashes in string

Hello,
I need to search a file for a computer name and replace it with a DFS path, for instance, search for all instances of

caetwk-srv3

and replace with

\\us\name1\name2\name3

How would this replace command look in sed??
Thanks in advance!
This is my easy job!
6 REPLIES 6
James R. Ferguson
Acclaimed Contributor
Solution

Re: Using SED with backslashes in string

Hi Theresa:

> How would this replace command look in sed??

Very ugly, like this:

# echo "caetwk-srv3"|sed -e s/caetwk-srv3/\\\\\\\\us\\\\name1\\\\name2\\\\name3/
\\us\name1\name2\name3

Regards!

...JRF...
James R. Ferguson
Acclaimed Contributor

Re: Using SED with backslashes in string

Hi (again) Theresa:

If you use Perl, you can greatly improve the readability and easily perform the desired substitution:

# echo "caetwk-srv3"|perl -pe 's{caetwk-srv3}{\\\\us\\name1\\name2\\name3}'

Regards!

...JRF...
Theresa Patrie
Regular Advisor

Re: Using SED with backslashes in string

Wow, thanks James for the quick response. So many backslashes!!!

My command looks like this and works fine

sed -e s/caetwk-srv3/us\\\name1\\\name2\\\name3/g inputfile >outputfile

Thank you very much!

P.S. There was already a double-backslash in front of caetwk-srv3, so I just left that alone and didn't have to insert any before "us"
This is my easy job!
James R. Ferguson
Acclaimed Contributor

Re: Using SED with backslashes in string

Hi Theresa:

NO POINTS FOR THIS, but I should have escaped the 'sed' program as:

# echo "caetwk-srv3"|sed -e 's/caetwk-srv3/\\\\us\\name1\\name2\\name3/'

Doing so would have negated the need for doubling the backslashes as I first did!

NO POINTS FOR THIS.

Regards!

...JRF...
Viktor Balogh
Honored Contributor

Re: Using SED with backslashes in string

You shouldn't use the slash as the separator character in sed. It can be some other character like . , ; #

But in this case you need to escape the characters because \name1 would be meant as a newline character with the string "ame1".

To clarify it, these also work:

# echo test | sed 's.test.TEST.'
TEST

and

# echo test | sed 's#test#TEST#'
TEST

But, as I said, in this case the special meaning of \n causes you another problem:

# echo caetwk-srv3 | sed 's.caetwk-srv3.\\us\name1\name2\name3.'
\us
ame1
ame2
ame3
#
****
Unix operates with beer.
Dennis Handly
Acclaimed Contributor

Re: Using SED with backslashes in string

>Viktor: You shouldn't use the slash as the separator character in sed.

Well in this case, "/" wasn't being used.

>But in this case you need to escape the characters because \name1 would be meant

You almost always need to escape "\" if you want a backslash. It doesn't matter if there was a "n".
Since it is in '', the shell doesn't see it but sed(1) has its own rules about "\".