16/04/2009
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 '
🙂
Filed by kargig at 20:50 under Linux
Tags: delete, directory, Linux, oneliner, xargs
4 Comments | 22,788 views
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 :}
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) 😉
find . -type d -empty -delete
Αυτό δεν είναι πιο εύκολο;
I guess you are correct Evaggelos…this seems to be the fastest, I didn’t know about “-delete” action of the find command.
Thanks 🙂