Thursday, December 19, 2013

Unix/Linux - Shell script to find and replace a text from the list of files

Below is the automated shell script which will find a text and replace it with the given string. It will also keep a backup of existing file. It can also be used for global search and replace string from a text file. Please see the self-explanatory shell script below -

replace.sh

#!/bin/bash

#find string
searchString="text1"

#replace with
replaceWith="text2"

echo "searching "$searchString" ..."
grep -l $searchString * >foundIn.txt
chmod 777 foundIn.txt

echo "replacing "$replaceWith" ..."
count=0
while read x
do
  if [ $x != replace.sh ]
  then
          (cat  $x) >$x"_bkp"
          sed "s/${searchString}/${replaceWith}/g" $x"_bkp" >  $x
          count=$(($count+1))
          echo "Found in... "$x
  fi
done <foundIn.txt

echo $count "occurences have been replaced."