LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Trying to replace '/' with '\/' in files using bash (https://www.linuxquestions.org/questions/linux-newbie-8/trying-to-replace-with-%5C-in-files-using-bash-747632/)

cg97330 08-14-2009 05:36 PM

Trying to replace '/' with '\/' in files using bash
 
Hi,

I'm using bash and am trying to find all / and replace with \/ in a line of text.

Basically, I want

/home/project/testfile

to become

\/home\/project\/testfile

I've tried many iterations of

sed -i s/'/'/'\/'/ testfile.dat

using single quotes, double quotes, and "\" to no avail. Any suggestions?

Thank you!

syg00 08-14-2009 06:06 PM

You need to escape the backslash - keep adding them (try 2, then maybe 3 depending on circumstance).

cg97330 08-14-2009 06:24 PM

Hmm, I can't seem to get it to work no matter how many I add. I was able to get around it using awk by changing the FS to /, and then printing each field with a \/ separator. I don't want to do it that way though, because I won't always know how many fields I have, so I'd have to write a loop.

syg00 08-14-2009 06:31 PM

Try
Code:

echo "/home/project/testfile" | sed 's:/:\\/:g'
The colon as separator is merely for readability - the manpage will explain the other change.

cg97330 08-17-2009 11:32 AM

Thanks so much! That worked perfectly.


All times are GMT -5. The time now is 10:42 AM.