Recursively replacing or removing a string from text files in a directory

I had a client with 3 WordPress sites hacked, having injected a dirty ad redirect in every possible javascript file of these sites. Around 1500 files were infected with one and the same script, so the best solution for curing them would be to remove that specific line that was causing all the trouble. Following set of bash commands did the trick, replacing all occurrences of OLD_STRING with NEW_STRING, in my case OLD being the beginning of the bad line of code and NEW being just //. As the rest of the malicious line was too complex to cover with a simple expression in the code below, I just opted for commenting the code instead of removing it totally.

find /home/user/location/of/files/ -type f -print0 | xargs -0 sed -i 's/OLD_STRING/NEW_STRING/g'



Leave a Reply

Your email address will not be published. Required fields are marked *