I want to delete all empty files with a particular extension from a directory and all its subdirectories.


You can try the following, to confirm upon deleting each file first:

$ find /path/to/dir -type f -name "*.txt" -empty -ok rm {} \;

or if you feel more confident:

$ find /path/to/dir -type f -name "*.txt" -empty -exec rm {} \;
  • 3
    On newer versions of find the -delete option will be simpler. – 0xC0000022L Feb 15 '12 at 17:34
  • keep in mind NOT to do this on the /dev directory – frogstarr78 Feb 16 '12 at 4:37

Usually, the answer to “how do I … in a directory and its subdirectories” involves find. Use -type f to match regular files, -name '*.ext' to restrict to a particular extension, and -size 0 to restrict to empty files.

find /some/dir -name '*.ext' -type f -size 0 -exec rm {} +

If your version of find is too old, you may need '… -exec rm {} \;' instead (using + is faster because it calls rm on many files at once). Under Linux, FreeBSD, NetBSD and OSX, you can use find's build-in -delete action and the -empty predicate (equivalent to -size 0 on regular files):

find /some/dir -name '*.ext' -type f -empty -delete

In zsh, you can use the ** glob to recurse into subdirectories and glob qualifiers to restrict the matches to regular files (.), of size 0 (L0).

rm /some/dir/**/*.ext(.L0)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.