LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   How can I replace this string with another using sed? (https://www.linuxquestions.org/questions/programming-9/how-can-i-replace-this-string-with-another-using-sed-346399/)

dave4545 07-24-2005 10:15 PM

How can I replace this string with another using sed?
 
Hey. I searched for answer before asking.
I couldn't seem to find anything that would help.
How can I use the search and replace feature using sed?
I need to replace some text on about 100 pages.

I wanted to find this
<!--#exec cgi="/cgi-bin/helper/adoption.pl" -->

and replace it with

<Script Language="JavaScript" Src="http://www.anysite/helper/one/help.php?help=adoption&r=1"></Script>";

basically I needed to change these tags on all files in a directory including the sub-directories.

I tried a few examples and got errors.
Your help will be greatly appreciated.
Thanks.
Dave.

Matir 07-24-2005 11:45 PM

Code:

sed 's/SEARCH/REPLACE/g' <infile >outfile
You will need to escape those search and replace fields above, but it should be fairly straightforward.

dave4545 07-25-2005 05:20 AM

Thanks.
I'll try it tonight when I get home from work.

mhoch3 07-30-2005 05:14 PM

Escape characters.... if the sed basic form is

sed s/SEARCHSTRING/REPLACESTRING/g

it is worth knowing that you don't have to use / as the delimiting character. You can use any character you please, pretty much. There are lots and lots of / in the expressions you want to search and replace and if you use / you will have to escape all of them. If instead you use ? which appears only once, or z which I think appears no-where in your urls you will have less escaping to do.

Best Wishes, Max

eddiebaby1023 07-31-2005 11:18 AM

And the '|' character is almost never present in strings to be matched.

desireuben 01-27-2006 09:25 AM

hey I also have the same problem. i tried what matir and mhoch3 suggested but the problem is i do not want to create new file with different name, i want to keep the same file name and modify it. if i use same name for infile and outfile, it wipes the file clean.what should i do ?

bigearsbilly 01-27-2006 10:16 AM

perl -pi.bak -e 's/this/that/g' file ... # make a backup

perl -pi -e 's/this/that/g' file ... # don't make a backup

Matir 01-27-2006 10:58 AM

Quote:

Originally Posted by desireuben
hey I also have the same problem. i tried what matir and mhoch3 suggested but the problem is i do not want to create new file with different name, i want to keep the same file name and modify it. if i use same name for infile and outfile, it wipes the file clean.what should i do ?

While bigearsbilly's solution may work, this does require the use of perl. Have you considered just making a temporary copy of the file? Like:

Code:

F=`mktemp`
sed '....' < INFILE > $F
mv $F INFILE
rm $F



All times are GMT -5. The time now is 07:09 AM.