1

How to remove folders and there content and keep files in the current directory ?

before

parent
├── folder1
├── folder2
│   ├── file1
│   ├── file2
├── folder3
├── file3
├── file4
└── file5

after:

parent
├── file3
├── file4
└── file5
2
  • 1
    What is the os you use? – Jake Mar 16 '16 at 9:44
  • I'm on a linux machine – Ghilas BELHADJ Mar 16 '16 at 9:46
3

Something like this should do the trick

cd parent
find . ! -path . -maxdepth 1 -type d -exec rm -rf {} \;

This will look for directories in the current working dir and only recurse 1 level down and the removes the dirs. Best do a testrun with ls instead of rm before doing this so you can check what will be removed

cd parent
find . ! -path . -maxdepth 1 -type d -exec ls {} \;

Example

jake@jake-HP /tmp/test $ tree
.
├── 1
├── 2
├── bar
│   ├── 1
│   ├── 2
│   └── 3
├── blah
│   ├── 1
│   ├── 2
│   └── 3
└── foo
    ├── 5
    └── 9

3 directories, 10 files
jake@jake-HP /tmp/test $ find . ! -path . -maxdepth 1 -type d -exec ls {} \;
1  2  bar  blah  foo
1  2  3
5  9
1  2  3
jake@jake-HP /tmp/test $ find . ! -path . -maxdepth 1 -type d -exec rm -rf {} \;
jake@jake-HP /tmp/test $ tree
.
├── 1
└── 2

0 directories, 2 files
4
  • I've just found the solution find . ! -path . -type d | xargs rm -R @Jake ! -path . is what you're looking for to exclude . folder – Ghilas BELHADJ Mar 16 '16 at 9:59
  • thanks ghilas-belhadj ! Edited the answer to include this. – Jake Mar 16 '16 at 10:35
  • To test better -exec ls -dF {} \; or -exec ls --color -dF {} \; just to avoid to list what inside the directories. – Hastur Mar 16 '16 at 12:34
  • Warning, the find | xargs rm will give unwanted results in the presence of directory names containing spaces or (even worse) special characters. – Law29 Mar 16 '16 at 12:42
0

Using find is good because you specify exactly what you want to be done. However the xargs in Jake's answer has a problem with directory names containing spaces. You'd need to add -print0 to find and -0 to xargs.

I would have written

find parent -type d -mindepth 1 -maxdepth 1 -exec rm -rf '{}' \;

This is even simpler:

rm -rf parent/*/

It won't remove hidden directories (starting with a period) though, you'd need to add them:

rm -rf parent/*/ parent/.[^.]*/

Watch out if you have symlinks pointing elsewhere, though.

If you don't trust */ to match only directories, a less clean solution that will produce lots of errors (and that does not take into account hidden directories because that gets complicated) is

rm -rf parent/*/* 
rmdir parent/*

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.