1

I have the following directory structure:-

foo/dir1/
foo/dir2/
foo/dir3/
foo/dir1/a.rb
foo/dir1/b.rb
foo/dir1/c.rb
foo/dir1/d.rb
foo/dir2/e.rb
foo/dir2/f.rb
foo/dir2/g.rb
foo/dir2/h.rb

How to remove zero byte files from a certain folder (some of the files under dir1, dir2 are zero bytes). How do I find and remove such files?

Rpj
  • 5,348
  • 16
  • 62
  • 122
  • [`du`](http://linux.about.com/library/cmd/blcmdl1_du.htm) may help point you in the right direction. – Aiias Apr 07 '13 at 06:48
  • 2
    This is an exact duplicate of the question [Remove all the files of zero size in specified directory](http://stackoverflow.com/questions/9907559/), but the other is closed 'off-topic' (which I don't agree with; shell programming is programming!), so I'm not sure it is a good idea to make this a duplicate of that question. – Jonathan Leffler Apr 07 '13 at 07:21
  • (Plus, I think the answer here is better than the answers in the possible duplicate — I think that's an objective assessment, but I am obviously not completely neutral on the subject.) – Jonathan Leffler Apr 07 '13 at 07:33

1 Answers1

13

Assuming you have a version of find compliant enough with POSIX 2008 to support the + notation:

find foo -size 0 -exec rm -f {} +

If you don't, there are variants you can use:

find foo -size 0 -print0 | xargs -0 rm -f   # But you probably have + anyway
find foo -size 0 -exec rm -f {} \;          # Slow but reliable
find foo -size 0 -print | xargs rm -f       # Fails with spaces etc in file names

And the accepted answer to the duplicate question suggests -delete, which is good when it is supported by the find you are using (because it avoids the overhead of executing the rm command by doing the unlink() call inside find):

find foo -size 0 -delete                    # Not POSIX standard
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    I think the `-0` stuff is older than the `+`, so there might be tool combinations who support `-0` but not `+`. – glglgl Apr 07 '13 at 07:27
  • 1
    @glglgl: you're right — there might still be really old platforms with `-print0` and `-0` and not `+`, so I'll modify the answer to be less categorical in that comment. – Jonathan Leffler Apr 07 '13 at 07:30