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
  • 66,199
  • 35
  • 114
  • 250

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
  • 47,463
  • 11
  • 118
  • 144
wyrm
  • 543
  • 2
  • 8
  • 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.

George Udosen
  • 1,807
  • 13
  • 26
  • 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

Praveen Kumar BS
  • 5,139
  • 2
  • 9
  • 14
  • I down voted, because [parsing the `ls` output](https://unix.stackexchange.com/questions/128985/why-not-parse-ls), plus because of using text processing tools after that too. – αғsнιη Dec 28 '17 at 13:35