Recursively delete files with find and rm

Written by
Date: 2020-03-01 16:15:32 00:00


First of all, I want to warn you that any command that may delete files should be used with care, you may break or badly damage your Linux and get no warning about what is going to happen. You will only notice when it is too late.

That said, I will show you how to delete files recursively, this is really powerful, and useful.

There are times when you really need to find files under some criteria, and erase them, we will use find and rm to achieve this.

find . -type f -name "criteria-to-find" -exec rm -f {} \;

This will find and remove and file that match the given criteria.

If you want to also delete directories, and not only files, you may use this one.

find . -name "criteria-to-find"-exec rm -rf {} \;

Once again, take care with this commands, and you may run first something like this:

find . -type f -name "*.txt" -exec ls {} \;

In this example we will list all *.txt files, once you are sure those files are the ones you want to delete, run this other command.

find . -type f -name "*.txt" -exec rm -rf {} \;