Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unix Shell scripting find and replace string in specific files in subfolders

Tags:

sed

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

  1. It also replaces the content of the script
  2. It replaces the text in all files of the subfolders( but I want only xml to change)
  3. I want to display error messages(text output preferably) if the text mismatch happens in a particular subfolder and file.

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

The script I have is :

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

like image 836
Sameer Shiraj Avatar asked Dec 16 '22 20:12

Sameer Shiraj


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
like image 143
perreal Avatar answered May 13 '23 03:05

perreal


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

Not sure I understand issue 3.

like image 25
John3136 Avatar answered May 13 '23 01:05

John3136