user5927908
user5927908

Reputation:

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

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?

Upvotes: 2

Views: 3985

Answers (2)

Tom
Tom

Reputation: 19

The command is:

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

Upvotes: 1

Ruslan Osmanov
Ruslan Osmanov

Reputation: 21522

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.

Upvotes: 3

Related Questions