Quick Linux rm find. Recursively delete files containing wildcards

I had to remove all backups that were contained on a specific mount point in a sub-directory called weekx recently.  This is the easiest way I found to do it.  Below will be an example using /test and /test/subfolder as the example:

Create files prefixed with asdf under the main /test folder
# touch asdf
# touch asdf1
# touch asdf3
# pwd
/test

Get a director listing to make sure the files were created
# ls
asdf  asdf1  asdf3  subfolder

Create a sub directory for testing as well
# mkdir subfolder

Create a prefixed asdf file in there also
# touch subfolder/asdf34
# touch subfolder/asdf35

Directory listing of subfolder
# ls subfolder/
asdf34  asdf35

To remove all files prefixed with asdf under a specific folder name, I issue the following
# rm `find /test/ -name “asdf*” | grep subfolder`

We now see that all files prefixed with asdf were removed from the subfolder
# ls subfolder/
#

All other asdf prefixed files are present under the /test directory
# ls
asdf  asdf1  asdf3  subfolder

Recreate a prefixed file under the subfolder

# touch subfolder/asdf4
# ls subfolder/
asdf4

To remove all files prefixed with asdf recursively from the /test file-system, issue the following command
# rm `find /test/ -name “asdf*”`

Doing a directory listing of /test and /test/subfolder will show that all asdf prefixed files have been removed
# ls -la | grep adsf
# ls
subfolder
# ls subfolder/

Note:  Check out this other blog for information on xargs and rm

http://blog.colovirt.com/2008/11/15/rm-files-using-xargs-another-argument-list-too-long/


~ by Kevin Goodman on October 22, 2008.

2 Responses to “Quick Linux rm find. Recursively delete files containing wildcards”

  1. pretty useful stuff, the * nearly destroyed my HDD lol.

  2. Ah, that sucks! Looks like the CSS template for the site is cutting off (overlaying) some of the “pre” formatted text.

Leave a Reply