How to Find and Delete Empty Directories and Files in Unix

by Ramesh Natarajan on March 12, 2010

Question: How do I locate empty directories that doesn’t contain any files? Also, how do I find all empty files ( zero byte files ) in Linux?

Answer: You can use unix find command to get a list of all empty files and directories as explained below.

Also, refer to our earlier articles about unix find command examples – part 1 and find command examples – part 2.

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.

Mommy, I found it! — 15 Practical Linux Find Command Examples tutorial explains find command’s maxdepth, mindepth, and invert match.

Download Free eBook - Linux 101 Hacks

Get free Unix tutorials, tips and tricks straight to your email in-box.

If you enjoyed this article, you might also like..

  1. 5 Practical Examples To Delete / Remove Directory in Linux
  2. tree and pstree: Visualize Unix Processes and Directories in Hierarchical Structure
  3. How to View and Delete Iptables Rules – List and Flush
  4. Unix Sed Tutorial: Delete File Lines Using Address and Patterns
  5. 7 Chmod Command Examples for Beginners
  

Vim 101 Hacks Book

{ 3 comments… read them below or add one }

1 Tester March 12, 2010 at 10:44 am

Very good way to delete it.

2 Tester2 March 14, 2010 at 4:57 pm

Why you don’t use the option “-delete” to delete the directories?

3 jameslee March 16, 2010 at 8:26 pm

really nice..very useful

Leave a Comment

Previous post:

Next post: