Find and replace from multiple files

Hello everybody, I need your help.
I have a php site that was expoited, the hacker has injected into many php files a phishing code that was discovered and removed in order to have again a clean code. Now we need to remove from many php files that malware. I need to create a script that find and remove from the files the bud code, in order avoid to do it manually. Mainly I think to a bash script where I can place the exact code to be searched into the files and recursively into the directories and than if the code is found it must be removed without altering the rest of the php code.
Could you please suggest me a solution of maybe a short script ( bash, php, perl or similar ) ?
Thanks in advance for your help.

I'm not sure your plan is the best but here is a suggestion, make a backup first even though there is garbage in there.:
If it is limited to php files (for example), then limit searching with find as step one, then use grep to see if the file is infected, and sed to remove bad strings - sed has to write to a tmp file which at the end of sed processing gets copied back and then re-set permissions/ownership.
psuedocode:

find /path/to/start  -type f -name '*php' |
while read fname 
do
   grep -q 'malware code pattern' $fname
   if [ $? -eq 0 ]; then
      sed 's/malware pattern//g' $fname  >/tmp/file
      mv /tmp/file $fname
      chown [required ownership] $fname
      chmod [required permissions] $fname 
   fi
done 

This has the potential of breaking some code. It also depends on how well you did checking for malware, it could simply reinfect your system if you missed something.
Be sure to get a good backup once the system is running correctly.

1 Like

Thank you for your kind reply.
Sorry but I forgot to tell you that the bud code I want to remove from the php files is very long string. That's why I want that the bash file read the string to be replace from a file. I have done the following modification to your script but this doesn't remove the code from the files, could you please help me with this ? What do I have to change ?

#!/bin/sh
VIRUS=virus
find /tmp/test/  -type f -name '*php' |
while read fname
do
   grep -q '$(cat virus)' $fname
   if [ $? -eq 0 ]; then
      sed 's/$(cat virus)//g' $fname  >/tmp/file
      mv /tmp/file $fname
   fi
done

Thank you in advance for your kind reply.