Delete files with string found in file - linux cli

Solution 1:

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

Solution 2:

@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

Solution 3:

You can use find's -exec and -delete, it will only delete the file if the grep command succeeds. Using grep -q so it wouldn't print anything, you can replace the -q with -l to see which files had the string in them.

find . -exec grep -q '[email protected]' '{}' \; -delete