Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete files with string found in file - linux cli

I am trying to delete erroneous emails based on finding the email address in the file via Linux CLI.

I can get the files with

find . | xargs grep -l [email protected]

But I cannot figure out how to delete them from there as the following code doesn't work.

rm -f | xargs find . | xargs grep -l [email protected]

Thank you for your assistance.

like image 961
Spechal Avatar asked Dec 25 '10 02:12

Spechal


People also ask

How do you delete a string from a file?

Retrieve the contents of the file as a String. Replace the required word with an empty String using the replaceAll() method. Rewrite the resultant string into the file again.

How do I delete a sed matching line?

To begin with, if you want to delete a line containing the keyword, you would run sed as shown below. Similarly, you could run the sed command with option -n and negated p , (! p) command. To delete lines containing multiple keywords, for example to delete lines with the keyword green or lines with keyword violet.


2 Answers

For safety I normally pipe the output from find to something like awk and create a batch file with each line being "rm filename"

That way you can check it before actually running it and manually fix any odd edge cases that are difficult to do with a regex

find . | xargs grep -l [email protected] | awk '{print "rm "$1}' > doit.sh vi doit.sh // check for murphy and his law source doit.sh 
like image 87
Martin Beckett Avatar answered Oct 14 '22 03:10

Martin Beckett


@Martin Beckett posted an excellent answer, please follow that guideline

solution for your command :

grep -l [email protected] * | xargs rm 

Or

for file in $(grep -l [email protected] *); do     rm -i $file;     #  ^ prompt for delete done 
like image 38
ajreal Avatar answered Oct 14 '22 02:10

ajreal