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,757 views