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
Super User is a question and answer site for computer enthusiasts and power users. It only takes a minute to sign up.
Sign up to join this communityHow 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
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
! -path .
is what you're looking for to exclude .
folder
– Ghilas BELHADJ
Mar 16 '16 at 9:59
-exec ls -dF {} \;
or -exec ls --color -dF {} \;
just to avoid to list what inside the directories.
– Hastur
Mar 16 '16 at 12:34
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
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/*