Linux: Find and remove matching files

I frequently use find to find all files matching a pattern and then delete them. I catch myself searching for the proper syntax to using this so I’m now going to blog it so I can find it easily from now on.

Lots of times I will use this technique to remove all “Thumbs.db” files from an NTFS, you know…the little database files that Windows XP by default automatically creates in every single folder that contains an image. They annoy me, so I use methods like the ones listed below to remove them.

If you want to use this, if will find all matching instances from the directory that you are in and following sub-directories. It will not search in parent directories.

The examples below will search for all Debian packages. Examples: this.deb, that.deb, those.deb, etc. Notice that the * is a wild card expression.

One simple way of doing this is:

username@host:~$ find . -name ‘*.deb’ -exec rm -f \{\} \;

The most common way of doing this is to use xargs, such that you don’t spawn one command for each file to be deleted:

username@host:~$ find . -name “*.deb” -print | xargs rm

(Note: Yes I’m ignoring files with spaces in their names.)

Here is another method that I found online that seems to be less common, but it makes the most sense of all three:

username@host:~$ find . -name “*.deb” -delete

You can also just use the following method to list the files in the terminal to make sure that the results are correct and to make sure that you want to delete them before you accidentally delete the wrong ones. ๐Ÿ˜‰

username@host:~$ find . -name “*.deb” -print

If the results are too long to fit in the terminal or you’d just like to have them in a text file then you can send the output to a text file instead by appending the following to the end of any command in the terminal.

> output.txt
(Here is an example)
username@host:~$ find . -name “*.deb” -printย > output.txt

If you know of any other methods, please feel free to share them!