5

So I used this to find all files in /directory that contain a code "test"

grep -R “test” /directory

Now I want to delete that code found in all the files in /directory at once.

Just that line of code for each file it is detected in.

UPDATE ***

I want to remove injected code @require(dirname(__FILE__).'/php/malware.php');

So this was done but it doesnt work. No error message shows. It just accepts the command.

grep -l -R '@require(dirname(__FILE__).'/php/malware.php');' /directory | xargs -I {} sed -i.bak 's/@require(dirname(__FILE__).'/php/malware.php');//g' {}

2 Answers2

7

Should pipe filenames to sed:

grep -l -R “test” /directory | xargs -I {} sed -i '/test/d' {}

Where:

Gonzalo Matheu
  • 8,984
  • 5
  • 35
  • 58
  • 1
    Great answer, if he wants to delete the whole line containing `test`. However he should use `sed` in replacement mode and change each line containing the `test` by an adequate replacement (eventually using back-reference) if he just want to remove the `test` part of the line and keep the rest of the line as-is. Finally, I would change the `-i` to `-i.bak` in order to keep a back up of the files just in case you know – Allan Dec 15 '17 at 01:59
4

You can use the following command if you want to remove only the test pattern of your files instead of deleting the whole line what will in most of the cases break your code:

grep -l -R 'test' /directory | xargs -I {} sed -i.bak 's/test//g' {}

It will replace globally the test pattern by nothing and also take a backup of your files while doing the operations! You never know :-)

If you are sure that you can delete the whole line containing the test pattern then you can use sed in the following way:

grep -l -R 'test' /directory | xargs -I {} sed -i.bak '/test/d' {}

You can after look for the backup files and delete them if they are not required anymore by using the following command:

find /directory -type f -name '*.bak' -exec rm -i {} \;

You can remove the -i after the rm if you do not need confirmation while deleting the files.

Allan
  • 12,117
  • 3
  • 27
  • 51