Computing.Net > Forums > Unix > Replace a string in Script

Replace a string in Script

Reply to Message Icon

Original Message
Name: martha911
Date: July 30, 2005 at 13:22:58 Pacific
Subject: Replace a string in Script
OS: Unix
CPU/Ram: Unix
Comment:

I need to create a script, taking a number of parameters (a target string, a string to replace the target string, and a number of files), that performs the substitution and a backup file creation when the target string occurs somewhre inthe file, but leaves the file completely unchanged if the string being replaced is no where in the file.
for example ./subst foo bar myFile1.txt myFile2.txt myFile3.txt
would repeat these steps on myFile1.txt, myFile2.txt, and myFile3.txt
1. Find the target string
2. If the target string is in the file, it would make a backup file from the file by adding .bak
If the target string is not in the file, it will do nothing
3. replace the string in the orginial file


This is my script...but somehow it is not correct:
#-------------------------

#!/bin/csh
set p1=$1
shift
set p2=$1
shift
foreach x ($*)
if ( { grep -w -c $p1 $x } ) then
mv $x $x.bak
sed 's/'$p1'/'$p2'/g' $x.bak > $x
else
endif
end
#--------------------------



Report Offensive Message For Removal


Response Number 1
Name: Luke Chi
Date: July 30, 2005 at 17:09:33 Pacific
Reply: (edit)

Replace: (single quote)

sed 's/'$p1'/'$p2'/g' $x.bak > $x

with: (double quote)

sed "s/$p1/$p2/g" $x.bak > $x

Luke Chi


Report Offensive Follow Up For Removal







Use following form to reply to current message:

   Name: From My Computing.Net Settings
 E-Mail: From My Computing.Net Settings

Subject: Replace a string in Script

Comments:

 


  Homepage URL (*): 
Homepage Title (*): 
         Image URL: 
 
Data Recovery Software




Have you ever used OpenOffice?

Yes, as my main suite.
Yes, occationally.
Yes, but only once.
No, never.


View Results

Poll Finishes In 5 Days.
Discuss in The Lounge