Linux delete file with size 0

LinuxFilesystemsDelete FileLsRm

Linux Problem Overview


How do I delete a certain file in linux if its size is 0. I want to execute this in an crontab without any extra script.

l filename.file | grep 5th-tab | not eq 0 | rm

Something like this?

Linux Solutions


Solution 1 - Linux

This will delete all the files in a directory (and below) that are size zero.

find /tmp -size 0 -print -delete

If you just want a particular file;

if [ ! -s /tmp/foo ] ; then
  rm /tmp/foo
fi

Solution 2 - Linux

you would want to use find:

 find . -size 0 -delete

Solution 3 - Linux

To search and delete empty files in the current directory and subdirectories:

find . -type f -empty -delete

-type f is necessary because also directories are marked to be of size zero.


The dot . (current directory) is the starting search directory. If you have GNU find (e.g. not Mac OS), you can omit it in this case:

find -type f -empty -delete

From GNU find documentation:

> If no files to search are specified, the current directory (.) is used.

Solution 4 - Linux

You can use the command find to do this. We can match files with -type f, and match empty files using -size 0. Then we can delete the matches with -delete.

find . -type f -size 0 -delete

Solution 5 - Linux

On Linux, the stat(1) command is useful when you don't need find(1):

(( $(stat -c %s "$filename") )) || rm "$filename"

The stat command here allows us just to get the file size, that's the -c %s (see the man pages for other formats). I am running the stat program and capturing its output, that's the $( ). This output is seen numerically, that's the outer (( )). If zero is given for the size, that is FALSE, so the second part of the OR is executed. Non-zero (non-empty file) will be TRUE, so the rm will not be executed.

Solution 6 - Linux

This works for plain BSD so it should be universally compatible with all flavors. Below.e.g in pwd ( . )

find . -size 0 |  xargs rm

Solution 7 - Linux

For a non-recursive delete (using du and awk):

rm `du * | awk '$1 == "0" {print $2}'`

Solution 8 - Linux

find . -type f -empty -exec rm -f {} \;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFranz KafkaView Question on Stackoverflow
Solution 1 - LinuxPaul TomblinView Answer on Stackoverflow
Solution 2 - LinuxJames.XuView Answer on Stackoverflow
Solution 3 - LinuxAntonioView Answer on Stackoverflow
Solution 4 - LinuxPYKView Answer on Stackoverflow
Solution 5 - LinuxcdarkeView Answer on Stackoverflow
Solution 6 - Linuxuser1874594View Answer on Stackoverflow
Solution 7 - LinuxHarrisonView Answer on Stackoverflow
Solution 8 - LinuxDiệu Thu LêView Answer on Stackoverflow