2012-01-30 110 views
3

我正在使用以下脚本来搜索并替换文件夹中的字符串。我如何修改代码以读取 从文本文件中读取多个$ searchname和$ replacename并替换原始文件夹中的单词?搜索并替换文件夹shell脚本中的字符串

这里的文件夹:

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

测试文件夹:

data.txt original/ script.sh tmp/ 

文件夹:

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

数据.TXT

a1 a2 
b1 b2 
c1 c2 

脚本搜索和替换:

!/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! *** " 

在此先感谢。

+0

顺便说一句,你可以'SED -i -e “S/$查找/替换$/G” $ file'做原地的'sed',这意味着没有必要'> tempfile'并重新命名。 – 2012-01-30 02:44:35

+0

谢谢,但我必须清理创建的备份文件(在-e结尾),我怎样才能发送修改后的文件到一个新的文件夹?谢谢 – john206 2012-01-30 03:43:18

回答

3

设置搜索的文件,并替换条款(我要去叫它search_and_replace.txt)看起来像:

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

那么你的bash脚本变为:

 
!/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 

无需用grep预搜索我想。

+0

我按照你的建议做了,但代码仅适用于search_and_replace_terms.txt的第一行 – john206 2012-01-30 04:00:18

+0

我猜你只有两行文件。尝试将新行添加到文件的末尾。有时候,如果没有行结束,只有文件结束,最后一行会被读取,但读取时会出现错误。 – 2012-01-30 04:39:24

+0

你说得对。我添加了一条新线,它的工作非常有魅力。非常感谢你。你能告诉我如何摆脱以-e或-e-e结尾的文件吗? – john206 2012-01-30 07:06:07

相关问题