Grep pattern in files if found delete the file

Recently I was presented with a problem where mail server was dying because of 100K+ mails in queue.

Due to spool overload it was necessary to identify a pattern and delete it from the /var/spool/postfix/incoming/ and later this needed to be applied for certain inboxes that were filled with spam.

Simplest way to find a pattern and if found was to use following command:

find -type f -exec grep -q "YOURPATTERN" '{}' \; -print

Be advised that this will print out all the mails/files that contain YOURPATTERN. If you are satisfied with matching result it’s easy to delete them with:

find -type f -exec grep -q "YOURPATTERN" '{}' \; -delete

For example one spammed inbox was containing 64305 messages with “Delivery Subsystem” as sender. To delete those messages I used:

find -type f -exec grep -q "Delivery Subsystem" '{}' \; -delete

After deletion of just that one pattern, inbox was down to 3534 mails.

So with just simple analysis and identification of spam mail and the right pattern you can delete all those unwanted files efficiently.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.