How do I delete all files with a given name in all subdirectories?

I want to delete all files with a given name in all the subdirectories of my home directory.

I tried:

rm -r file

in my home directory, but it didn’t work because that file doesn’t exist in that directory.

Asked By: oadams


find . -name "filename" -delete

Answered By: tante

as an elaboration on @tante’s answer, you may wish to ensure the file list used is correct before deleting those files:

find <source_dir> -name <filename> -print

if inspection shows valid list then

find <source_dir> -name <filename> -delete

another option if wanting this over many directories using a temporary holding directory:

mkdir <dest_dir>
for i in <list_of_directories>
  find "$i" -name <filename> -exec /bin/mv {} <dest_dir>

# check dest_dir
ls dest_dir
rm -rf <dest_dir>

As always, please ensure the accuracy of any scripts before execution and always have a backup ready in-case something goes wrong.

Answered By: Wayne
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.