7

I'm trying to delete the content of some directories (but not the directory itself) using this:

find -type d -name someDirs -exec rm -rf {}/* \;

But it doesn't work. Any tips?

5

The problem with your command is that wildcard expansion is done by your shell before the command is actually called. As your shell does not find a file that matches {}/* (as you don't have a directory with a literal name {} in the current directory), the * is passed to the command unchanged, which will then be modified by find to delete files named literal * in your someDirs directories, as the rm command will not expand wildcards (again). You can "debug" this by running

find -type d -name someDirs -exec echo rm -rf {}/* \;

instead. To make sure that the shell has a chance to expand your *, let exec spawn another shell which can expand the * (and protect the command from being expanded first with single quotes) like this:

find -type d -name someDirs -exec sh -c 'rm -rf {}/*' \;

or test it like this:

find -type d -name someDirs -exec sh -c 'echo rm -rf {}/*' \;
9

You can give the directory (or directories) as arguments to find and tell it to skip it with the -mindepth option:

-mindepth levels
Do not apply any tests or actions at levels less than levels (a non-negative integer).
-mindepth 1 means process all files except the command line arguments.

So, your command would be:

find SomeDir1 SomeDir2 -mindepth 1 -exec rm -rf '{}' \+
6
  find . -type f -delete

will delete all files in and below the current directory, leaving the directory structure alone.

If your find command doesn't support -delete (it's slightly modern, but been there fore a few years now), then:

  find . -type f -exec rm {} \;

Edit: As noted by Nate, this is not the right answer.

  • It looks to me like the OP wants to delete not only the files but also the directories under someDirs, just not someDirs itself. So we don't actually want to leave the directory structure alone. I left a comment requesting clarification. – Nate Eldredge Dec 31 '14 at 20:43
  • If so, cd somdDirs && rm -r * will do the trick but is extremely scary to post :) – Craig Miskell Dec 31 '14 at 20:45
  • As I read it, there may be many directories named someDirs, possibly at different depths below the current directory. – Nate Eldredge Dec 31 '14 at 20:46
  • Ahhh, I see. Good point. – Craig Miskell Dec 31 '14 at 20:47
  • Maybe something with -regex or -path, but I don't feel comfortable recommending anything (the risk is... high :)) – Craig Miskell Dec 31 '14 at 20:52

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.