I thought up of the following BASH one-liner half an hour ago to remove lots of empty or zero byte files from a directory. I have prettified the presentation of the one-liner below, but you may safely pull all the lines together into a single line and use it on BASH. Do note that the actual command to remove the files has been stashed inside an echo command for safety.
for file in *;
do
file_size=$(du $file | awk ‘{print $1}’);
if [ $file_size == 0 ]; then
echo “Deleting empty file $file with file size $file_size!”;
echo “rm -f $file”;
fi;
done
5 Comments
find|xargs will change your life then :)
find -maxdepth 1 -type f -empty -print0|xargs -0 echo rm -f
(Note the echo failsafe)
I’ve another way still - but first…
Using find -print0 and xargs -0 implies GNU find and GNU xargs - which are not always present. Also, xargs requires a binary and echo is a builtin - but since it is usually ALSO a binary, it may be okay.
Here’s my alternative:
for i in * ; do [ ! -s "${i}" ] && echo rm -f “${i}” ; done
This should be fastest: there is only one binary in this sequence; the rest are builtins.
Depending on how many there are, this might even be faster:
echo rm -f $(for i in *; do [ ! -s "$(i)" ] && echo $i)
Again, no binaries but rm - but in this case only one rm call, not one for each file.
(note the echo failsafe here as well)
Ayaz bhai!
rm -f $(find . -empty)
Give it a try :p
@azimyasin: ingenious!
However, there are two flaws: 1) the find command will descend indefinitely; 2) that command will delete empty directories as well.
How about:
rm -f $(find . -maxdepth=1 -type f -empty)However, it still requires loading find and rm instead of just rm; my examples used shell built-ins for their speed.
Those examples are also compliant with ksh, not just bash I might add.
find . -size 0 -exec rm -f ‘{}’ \;
:D
Post a Comment