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

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

Replace a string in Script

Reply to Message Icon

Name: martha911
Date: July 30, 2005 at 13:22:58 Pacific
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
#--------------------------




Sponsored Link
Ads by Google

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

Replace: (single quote)

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

with: (double quote)

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

Luke Chi


0
Reply to Message Icon

Related Posts

See More


find unwanted characters ... finding whether a file is...



Post Locked

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.


Go to Unix Forum Home


Sponsored links

Ads by Google


Results for: Replace a string in Script

replacing a string in a file www.computing.net/answers/unix/replacing-a-string-in-a-file/6138.html

how to replace a file in a .zip fil www.computing.net/answers/unix/how-to-replace-a-file-in-a-zip-fil/7497.html

how to replace a line in a file www.computing.net/answers/unix/how-to-replace-a-line-in-a-file/7214.html