Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
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
#--------------------------

Replace: (single quote)
sed 's/'$p1'/'$p2'/g' $x.bak > $x
with: (double quote)
sed "s/$p1/$p2/g" $x.bak > $x
Luke Chi

![]() |
find unwanted characters ...
|
finding whether a file is...
|

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