Unix Shell Scripts Find and Replace a String in Specific Files in Subfolders

I want to replace the line "Solve a problem" with "Choose the best answer" only in xml files that exist in the subfolders of the folder. I compiled a script that helps me do this, but there are 2 problems

  • It also replaces the contents of the script.
  • It replaces the text in all subfolder files (but I want to change only xml)
  • I want to display error messages (preferably text output) if text mismatch occurs in a specific subfolder and file.

So, can you help me modify my existing script so that I can solve the above problems.

script I have:

find -type f | xargs sed -i "s / Solve the problem / Choose the best answer / g"

+4
source share
2 answers

Using bash and 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 
+8
source
 find -type f -name "*.xml" | xargs sed -i "s/Solve the problem/Choose the best answer/g" 

Not sure I understand the problem 3.

+3
source

All Articles