I need a little help with a shell script. I want to be able to specify parameters so that the script searches multiple files (specified as parameters) and only modifies the file if it finds the string of text. For the files it doesn't find the string of text within, it should leave it alone.
So far, it seems like it only checks the first file and if that one is "true", it creates a .bak file for the remaining files (or vice versa if the first text file comes back as "false". It is replacing the text in all text files specified, but it is creating the .bak files when it is not necessary.
As an example, If i have four text files: text1.txt, text2.txt, text3.txt text4.txt, I would want to have the script look through each file, see if the string of text exists and then replace the string only if it exists, such as:
The files to be replaced aren't necessarily .txt files. For example, one time running the script, I may want to replace a variety of .txt and .dat files, another time I may want to only want to replace .dat files or .txt files, etc.
The code I have now does replace the text successfully in all the files I specify. However, I want the files to not be touched/modified if grep does not find the string of text in the file.
---------- Post updated at 01:54 AM ---------- Previous update was at 01:37 AM ----------
I figured out what I was doing wrong. The $SEARCH variable shouldn't have been set as a global variable. It should have been within the "if" loop, such as:
#!/bin/sh
p1=$1
p2=$2
while [ ! -z "$3" ]
do
SEARCH=`grep $p1 $3 | wc -l`
if [ $SEARCH -ge 1 ]
then
mv $3 $3.bak
sed -e "s/$p1/$p2/g" $3.bak > $3
shift
else
shift
fi
done
# test number of args
[ "$#" -lt 2 ] && exit 1
str="$1"
strnew="$2"
# destroy first args
shift 2
# loop rest args
for infile in $*
do
# grep return exit <>0 if not true = continue = next file
grep "$str" "$infile" >/dev/null 2>&1 || continue
# include $str, replace, save original (.bak)
bak="$infile.bak"
mv "$infile" "$bak"
sed "s/$str/$strnew/g" "$bak" > "$infile"
done
; need only if you have more than one command in the same line