How to remove all files that are empty in a directory?

3.5k views Asked by At

Suppose I've got a directory that looks like:

-rw-r--r-- 1 some-user wheel 0 file1
-rw-r--r-- 1 some-user wheel 257 file2
-rw-r--r-- 1 some-user wheel 0 file3
-rwxr-xr-x 1 some-user wheel 212 file4
-rw-r--r-- 1 some-user wheel 2012 file5
.... more files here.

If it's relevant, assume that the names of the files are more random than just file#.

How do I remove only the files that are empty (meaning that the file has 0 bytes in it) in a directory, using rm and grep or sed in some form?

2

There are 2 answers

2
Ruslan Osmanov On BEST ANSWER

The easiest way is to run find with -empty test and -delete action, e.g.:

find -type f -empty -delete

The command finds all files (-type f) in the current directory and its subdirectories, tests if the matched files are empty, and applies -delete action, if -empty returns true.

If you want to restrict the operation to specific levels of depth, use -mindepth and -maxdepth global options.

1
Tom On

The command is:

cd DirectoryWithTheFiles
rm -f $(find . -size 0)