delete all empty directories using xargs

I was trying to figure out one 1-liner to delete all empty directories in a tree.
The following should do it’s job:
%find -type d -empty | xargs rm -rvf

BUT! While this works for directories with “regular” filenames, it doesn’t work when there are special characters inside the filename. Consider this for example:

%ls -1
test 1
test2
test _ 3
%find -type d -empty
./test 1
./test2
./test _ 3
%find -type d -empty | xargs rm -rvf
removed directory: `./test2'
%find -type d -empty
./test 1
./test _ 3

Only directory “test2” was deleted. To delete the rest of the directories when they contain “special” characters like whitespace and quotes one needs to modify the command like this:

%find -type d -empty -print0 | xargs -0 rm -rvf
removed directory: `./test 1'
removed directory: `./test _ 3 '

🙂

4 Responses to “delete all empty directories using xargs”

  1. scarabeus
    April 17th, 2009 | 01:00
    Using Konqueror Konqueror 4.2 on Linux Linux

    find -type d -empty -print0 | xargs -0 rm -rvf
    find -type d -empty | xargs -i rm -rvf {}
    find -type d -empty -print0 -exec rm -rvf {} \;

    Pick your favorite :}
    Maybe try to compare their speed and pick fastest :}

  2. April 20th, 2009 | 23:09
    Using Mozilla Firefox Mozilla Firefox 3.0.8 on Ubuntu Linux Ubuntu Linux

    Don’t use xargs at all, just use -delete in find (available in findutils for about 2 years now, so in every ‘recent’ distro)..

    Better (no need for special modifications to xargs) and faster (avoid the pipe altogether) 😉

  3. April 21st, 2009 | 12:52
    Using Mozilla Firefox Mozilla Firefox 3.0.8 on Linux Linux

    find . -type d -empty -delete

    Αυτό δεν είναι πιο εύκολο;

  4. April 21st, 2009 | 13:15
    Using Mozilla Firefox Mozilla Firefox 3.0.8 on Mac OS X Mac OS X 10

    I guess you are correct Evaggelos…this seems to be the fastest, I didn’t know about “-delete” action of the find command.

    Thanks 🙂

Leave a reply