我正在使用以下脚本来搜索和替换文件夹中的字符串。如何修改要读取的代码 从文本文件中读取多个$ searchname和$ replacename并替换原始文件夹中的单词?
这是文件夹:
main folder: /USERS/path/to/test/
在测试文件夹中:
data.txt original/ script.sh tmp/
在原始文件夹中:
file1.txt file2.php ...........
data.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 :(得分: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进行预搜索。