3

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.

2
  • As an aside, you can sed -i -e "s/$search/$replace/g" $file to do the sed in-place, meaning no need to > tempfile and rename. Commented Jan 30, 2012 at 2:44
  • Thanks but then I have to clean up backup files created (with -e at their ends), how can i send modified files to a new folder? thanks Commented Jan 30, 2012 at 3:43

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I did as you suggested but the code worked only for the first line in search_and_replace_terms.txt
I'm guessing you only had two lines in the file. Try adding a newline to the end of the file. Sometimes if there's no end-of-line, only an end-of-file, the last line gets read but read exists with an error.
You were right. I added a new line and it worked liked a charm. Thank you very much. Would you please tell me how can I get rid of files ending with -e or -e-e ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.