2012-08-08 74 views
4

我想在僅存在於文件夾子文件夾中的xml文件中將「解決問題」字符串替換爲「選擇最佳答案」。我編了一個腳本,它可以幫助我做到這一點,但也有2個問題Unix Shell腳本查找並替換子文件夾中特定文件中的字符串

  1. 它也取代了腳本的內容
  2. 它將替換子文件夾中的所有文件的文本(但我只想要XML以改變)
  3. 如果文本不匹配發生在特定的子文件夾和文件中,我想顯示錯誤消息(最好是文本輸出)。

所以,你能幫我修改我現有的腳本,以便我可以解決上述3個問題。

腳本我有是:

發現型的F | xargs的sed的-i 「S /解決問題/選擇最佳答案/ G」

回答

8

使用bash和sed:

search='Solve the problem' 
replace='Choose the best answer' 
for file in `find -name '*.xml'`; do 
    grep "$search" $file &> /dev/null 
    if [ $? -ne 0 ]; then 
    echo "Search string not found in $file!" 
    else 
    sed -i "s/$search/$replace/" $file 
    fi 
done 
+0

多數民衆贊成有幫助...謝謝:) – 2012-08-18 08:21:30

3
find -type f -name "*.xml" | xargs sed -i "s/Solve the problem/Choose the best answer/g" 

不知道我理解發行3

+0

這解決我的問題...謝謝約翰:) – 2012-08-18 08:21:02

相關問題