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?


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).

| improve this answer | |
  • 1
    if -delete doesn't work, use "find . -type d -empty -exec rmdir {} \;" (don't forget the space behind {}, it's important). – FSMaxB Feb 5 '13 at 19:07
  • You may need an explicit -depth with find, 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. – mr.spuratic Feb 5 '13 at 20:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.