String Replacement Script

Okay, I have a script right now that is made to search through a file and replace certain strings with a new one. The format to execute is "/subst <replacethis> <withthis> <filename>" and it only updates the file IF changes are made (in order to preserve the time it was made/last modified). I have this working 100% right now, but the next step is to edit the script so that it is possible for users to do "/subst <replacethis> <withthis> <filename> <filename2> <filename3> <filenamex>" as high as they want. If anyone can point me in the right direction of methods to do this or simply fix it for me, I would be very greatful.

Here is my current script:

#!/bin/bash

replacethis=$1
withthis=$2
file=$3

sed -e "s+$replacethis+$withthis+g" $file > $file.bak

cmp $file $file.bak > /dev/null
if [ $? -eq 0 ]
then
  echo "Files are the same, nothing was replaced."
  rm $file.bak
else  
  mv $file.bak $file
fi

Thanks in advance for anyone that can help!

#!/bin/bash

replacethis=$1
withthis=$2

shift 2

for file in $@
do
  sed -e "s+$replacethis+$withthis+g" $file > $file.bak

  cmp $file $file.bak > /dev/null
  if [ $? -eq 0 ]
   then
    echo "Files are the same, nothing was replaced."
     rm $file.bak
  else  
    mv $file.bak $file
  fi
done

Thank you very much, works perfectly :slight_smile:

Hello All,

i have a problem which is exactly similar to this in all respects except that i have to do this for all files in the directory including sub-directories in which the pattern exists.

the code did work for me too, just it will be great if anybody can give a solution which works for all files in all the sub-directories as well.. this is becoz, there are too many files and i don't remember them all..

Will be very grateful to all of you..

find directory -type f | xargs -n 1 thatotherscript replacethis withthis

and if want to remove the case dependency of the string being searched?

pranavagarwal,
Please do not bump up your posts. Your other thread is Need shell/sed script for grep+string replacement