Recursively delete certain files

Contributor Icon Contributed by qmchenry  
Tag Icon Tagged: UNIX  

Using the find command, you can locate and delete files based on many attributes such as filetype. This 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 would be a dangerous command to execute, so 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:

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

 

4 Comments -


  1. Anonymous said on October 5, 2009

    Why does the following not work, recursively?

    rm -vR folderToStartAt/*ext

  2. daffodil said on August 26, 2010

    if i have file list say FILE_LIST=”a.txt b.txt c.txt” pls tell me how to delete this with one command. i.e not using any loops.

  3. Jim Power said on September 18, 2010

    How can I make this work if I have directories/files with spaces in the name?

  4. User said on October 27, 2010

    Jim- prepend the space with a backslash. Example:
    /home/user/My Folder With Spaces/file.txt

 

RSS feed for comments on this post. TrackBack URL

Leave a comment -