john206
john206

Reputation: 547

Search and replace string in folder shell script

I'm using the below script to search and replace string in a folder. How can i modify the code to read read multiple $searchname and $replacename from a text file and replace the words in original folders?

here are the folders:

main folder: /USERS/path/to/test/

inside test folder :

data.txt   original/  script.sh  tmp/

inside original folder :

file1.txt file2.php ...........

inside data.txt:

a1 a2
b1 b2
c1 c2

script for search and replace:

 !/bin/bash

 FOLDER="/Users/path/to/test/original/"
 echo "******************************************"
 echo enter word to replace
 read searchterm
 echo enter word that replaces
 read replaceterm



   for file in $(grep -l -R $searchterm $FOLDER) 


      do

   sed -e "s/$searchterm/$replaceterm/g" $file > /Users/path/to/test/tmp/tempfile.tmp 
       mv /Users/path/to/test/tmp/tempfile.tmp $file

       echo "Modified: " $file

    done




   echo " *** All Done! *** "

Thanks in advance.

Upvotes: 3

Views: 3820

Answers (1)

thinkski
thinkski

Reputation: 1302

Setup the file of search and replace terms (i'm going to call it search_and_replace.txt) to look like:

searchone/replaceone
searchtwo/replacetwo
foo/bar
...

Then your bash script becomes:

!/bin/bash

FOLDER="/Users/path/to/test/original/"

while read line; do
    for file in `find $FOLDER -type f`; do
        sed -i -e "s/$line/g" $file
    done
done < search_and_replace_terms.txt

No need to pre-search with grep I think.

Upvotes: 3

Related Questions