LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   How to replace all occurances of a complex string using sed (https://www.linuxquestions.org/questions/programming-9/how-to-replace-all-occurances-of-a-complex-string-using-sed-574390/)

6millionbucks 08-03-2007 12:15 AM

How to replace all occurances of a complex string using sed
 
Can someone tell me what Im doing wrong. Im trying to replace all occurances of one string with another string.

I want to replace all occurances of downloads/index.php?folder/200706/ with dwnld/new_index.php?p= in a file called va_200706.php

I've tried the following:

Code:

cat va_200706.php | sed 's/\downloads/index.php?folder/virginia/200706/\/\dwnld/dl.php?p=\/g' > va_200706_new.php
as well as

Code:

cat va_200706.php | sed 's/[downloads/index.php?folder/virginia/200706/]/[dwnld/dl.php?p=]/g' > va_200706_new.php
There was a similiar question posted in which the solution was to use

sed s/SEARCHSTRING/REPLACESTRING/g

but I think the / in my strings are messing things up.

rkelsen 08-03-2007 12:23 AM

Quote:

Originally Posted by 6millionbucks
but I think the / in my strings are messing things up.

You need to 'escape' special characters with backslashes.

Eg:

Code:

sed 's/downloads\/index.php\?folder\/200706\//dwnld\/new_index\.php\?p\=/'

syg00 08-03-2007 12:29 AM

And you don't even need to escape the "?" if IIRC. (or the "=" ???).

6millionbucks 08-03-2007 12:35 AM

SOLVED: how to replace all occurances of a complex string
 
Thanks rkelsen, the backslashes did it.

Heres what I ended up using and it worked wonderfully:

Code:

sed 's\downloads/index.php?folder/virginia/200706\dwnld/dl.php?p=\g' <va_200706.php >va_200706_new.php

archtoad6 08-12-2007 11:45 AM

I would have written that as:
Code:

sed 's,downloads/index.php?folder/virginia/200706,dwnld/dl.php?p=,g' <va_200706.php >va_200706_new.php
The principle is the same: the 1st character after the 's' is the regex delimiter. AFAIK, any character may be chosen. I think using '\' is not desirable because then it cannot be used in its normal "escape character" role.

I have come to prefer ',' as my personal standard delimiter, but I have friends who use '!' or '#'. It's a matter of taste.

Although you would not want to use it here because it would require escaping the '?', you might also want to add the sed "-r" to your repertoire -- see the man page.

/bin/bash 08-12-2007 11:55 AM

Also sed can edit the file directly using -i switch and will even make a backup copy.
Code:

sed -i.bak 's\downloads/index.php?folder/virginia/200706\dwnld/dl.php?p=\g' va_200706.php
The above edits the file va_200706.php and creates backup file va_200706.php.bak

/bin/bash 08-12-2007 11:55 AM

oops too many clicks


All times are GMT -5. The time now is 12:22 PM.