Recursively Delete Certain Files

Posted September 30, 2003 by Quinn McHenry in UNIX

Using the find command, you can locate and delete files based on many attributes such as filetype. This tech-recipe will demonstrate how to find and delete files based on part of their filename.


To find and delete all files on the system that end in .log, run this as superuser:

find / -name \*.log -exec rm {} \;

The backslashes (\) are important in this command. Using the -exec option allows an arbitrary command, in this case rm, to be used with the filename substituted in place of the {} characters.

This command would be dangerous to execute. A safer alternative uses the -ok command instead of the -exec. When used this way, find will prompt you before each execution of the command following -ok. To optionally delete all files ending with .tmp in the /var filesystem, use the following:

find /var -name \*.tmp -ok rm {} \;

 

About Quinn McHenry

Quinn was one of the original co-founders of Tech-Recipes. He is currently crafting iOS applications as a senior developer at Small Planet Digital in Brooklyn, New York.
View more articles by Quinn McHenry

The Conversation

Follow the reactions below and share your own thoughts.