Linux / Unix: Find and Delete All Empty Directories / Files
شنبه, ۱۷ خرداد ۱۳۹۳، ۰۶:۱۵ ق.ظ
Method # 1: Find and delete everything with find command only
The syntax is as follows to find and delete all empty directories:
find /path/to/dir -empty -type d -delete
Find and delete all empty files:
find /path/to/dir -empty -type f -delete
Where,
- -empty : Only find empty files and make sure it is a regular file or a directory.
- -type d : Only match directories.
- -type f : Only match files.
- -delete : Delete files. Always put -delete option at the end of find command as find command line is evaluated as an expression, so putting -delete first will make find try to delete everything below the starting points you specified.
Method # 2: Find and delete everything using xargs and rm/rmdir command
The syntax is as follows to find and delete all empty directories:
## secure and fast version ### find /path/to/dir/ -type d -empty -print0 | xargs -0 -I {} /bin/rmdir "{}"
OR
## secure but may be slow due to -exec ## find /path/to/dir -type d -empty -print0 -exec rmdir -v "{}" \;
The syntax is as follows to delete all empty files:
## secure and fast version ### find /path/to/dir/ -type f -empty -print0 | xargs -0 -I {} /bin/rm "{}"
OR
## secure but may be slow due to -exec ## find . -type f -empty -print0 -exec rm -v "{}" \;
- ۹۳/۰۳/۱۷