Wednesday, January 25, 2012

How to Find and Delete Empty Directories and Files in Unix


Find empty directories in the current directory using find -empty

find . -type d -empty
Use the following command to remove all empty directories under the current directory.
find . -type d -empty -exec rmdir {} \;
Note: It is not recommended to remove empty directories from /etc/ or any other system directories.

Find empty files in the current directory using find -empty

find . -type f -empty
Note: Typically empty files are created by some programs as place holders, or as lock files, or as socket files for communication.

How many empty files are located under the current directory (and sub-directories)?

To count the number of empty files under current directory, pipe the find command to wc -l
find . -type f -empty | wc -l

How many non-empty files are located under the current directory (and sub-directories)?

find . -type f -not -empty | wc -l
Note: Find option -not reverts the option that follows it.
In all the above examples, replace the ( . ) dot with any other directory-path under which you would like to search the files.