简体   繁体   中英

How to find a line of code and delete that line from all files in a certain /directory only, using Linux CLI

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' {}

Should pipe filenames to sed :

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

Where:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM