I want to delete all empty files with a particular extension from a directory and all its subdirectories.
2 Answers
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
-
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)