Unix Shell脚本在子文件夹中的特定文件中查找和替换字符串

Sam*_*raj 4 sed

我想仅在文件夹的子文件夹中存在的xml文件中用"选择最佳答案"替换字符串"解决问题".我编写了一个脚本来帮助我做到这一点,但有两个问题

  1. 它还替换了脚本的内容
  2. 它取代了子文件夹的所有文件中的文本(但我只想更改xml)
  3. 如果文本不匹配发生在特定的子文件夹和文件中,我想显示错误消息(最好是文本输出).

那么请你帮我修改我现有的脚本,以便我可以解决上述3个问题.

我的脚本是:

find -type f | xargs sed -i"s /解决问题/选择最佳答案/ g"

per*_*eal 9

使用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
Run Code Online (Sandbox Code Playgroud)