Linux, find all files matching pattern and delete

Looking to find all files (recursively) which have an underscore in their file name and then delete them via command line.


Solution 1:

This is the safest and fastest variant:

find /path -type f -name '*_*' -delete

It does not require piping and doesn't break if files contain spaces or globbing characters or anything else that other constructs would choke on. The easiest rule to remember here is to never parse find output. And never grep on filenames if you want to do something with them later. You can do almost anything with find directly.

See also: GNU find Manual – Deleting Files

Solution 2:

This includes directories which are considered files. Some of the other examples using xargs will fail if the filename contains spaces.

find . -name '*_*' -exec rm -rf {} \;

If you only want regular files:

find . -type f -name '*_*' -exec rm -f {} \;