2

Basically, I want to delete all subfolders, but leave all the files intact. For example:

Folder1/
    randomStuff/
         nope.txt
    installer.jar
    build.sh

I want randomStuff and its files deleted, but keep installer.jar and build.sh intact.

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255

3 Answers3

9

Use the fact that a filename that ends in a slash always refers to a directory, and never a regular file.

The command

rm -r -- ./*/

will accomplish what you describe.

chaos
  • 48,171
wyrm
  • 543
  • 5
    rm -r ./*/, rm -r -- */, or rm -r -- ./*/ please. – jesse_b Dec 28 '17 at 03:21
  • 1
    @saga, huh? The original was rm -r */, which, in an empty directory expands to rm -r */, which will give an error from rm since the file/directory * doesn't exist. If there was a directory named -f, it would be added to the command line as -f/, which would probably give an error about an invalid option /. Even with nullglob set, the whole word would disappear, not just the asterisk, so rm would still complain about a missing target. I can't see how that could target the user's home directory? – ilkkachu Dec 28 '17 at 11:08
  • Sure, in general it's a good idea to protect against file names being taken as options to the command, but I think the most dangerous one for rm is -r, which was already given here. – ilkkachu Dec 28 '17 at 11:09
1

Try this:

find Folder1/* -type d -exec rm -rf {} +

This will search for folders within that directory and run the rm -rf command on each found.

  • 1
    Why '+'? It will make the command unnecessarily slow. Adding -depth 1 wouldn't hurt. – saga Dec 28 '17 at 09:35
-1

I used awk command to achieve the same.


ls -ltr | awk '$1 ~ "^dr"{print "rm -rvf" " " $9}’ | sh