I have a directory containing lots of files and lots of empty directories. I want to keep the files but remove the directories. How can I achieve this using rm
and other standard unix tools?
1 Answer
Something along the lines:
find . -type d -empty -delete
I believe the -delete
is a GNUism, in which case you have to do:
find . -type d -empty -print0 | xargs -0 rm
This handles the case of file names with "strange" characters (but it seems -print0
and -0
are again GNU extensions).
-
1if -delete doesn't work, use "find . -type d -empty -exec rmdir {} \;" (don't forget the space behind {}, it's important).– FSMaxBFeb 5, 2013 at 19:07
-
You may need an explicit
-depth
withfind
, depending on the invocation, so that deeper directories are removed first.-delete
automatically uses-depth
, the "find ... -print0 | xargs
" version does not, and would leave file-less directory hierarchies undeleted. Feb 5, 2013 at 20:45