2012-01-30 108 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

相關問題