0

If the folder structure is:

parentFolder
├── file1.rtf
├── file2.rtf
... #there are many more files.
├── moreFiles.rtf
├── subFolder1
├── subFolder2
├── subFolder3
... #there are many more subfolders.
└── moreSubFolders

How would I delete all subfolders except subFolder1 without deleting any of the files?

I do not want to have to name each folder which should be deleted.

I also do not want to have name each file which should not be deleted.

I want a command that only deletes folders, not files, and allows the user to exclude some folders from being deleted.

6
  • Welcome to Ask Different :) Unless I am interpreting the question incorrectly, what's wrong with running rm -rf parentFolder/subFolder1?
    – Nimesh Neema
    Commented Aug 20, 2020 at 22:50
  • Just to rephrase the question to make it clearer, are you trying to delete jsut the empty subfolders?
    – Allan
    Commented Aug 21, 2020 at 0:03
  • @NimeshNeema I should have been more clear that there are MANY (twenty or so) subfolders. Updated.
    – Jack
    Commented Aug 21, 2020 at 5:36
  • @Allan whether the subfolder is empty or not does not matter. I'm just trying to delete some of the subfolders
    – Jack
    Commented Aug 21, 2020 at 5:37
  • Perhaps you can approach the problem by considering copying/moving files rather than deleting, which can be problematic if files get deleted by accident.
    – IconDaemon
    Commented Aug 21, 2020 at 15:13

1 Answer 1

1

Rule-based deletions tend to be tricky and can easily go wrong. In your case the following might work

find "parentFolder" -depth 1 -type d ! -name subFolder1 -ok rm -r -- '{}' \;

This

  • only looks one level beneath parentFolder (-depth 1)
  • only looks at directories (-type d)
  • skips subFolder1 (! -name subFolder1)
  • prompts for the deletion of any non-skipped directories (-ok rm -r -- '{}' \;)

PS: To skip several directories use ! \( -name subFolder1 -o -name subFolder2 \), to delete without prompting use -exec rm -r -- '{}' +.

4
  • might need to escape the ! as \!
    – TJ Luoma
    Commented Aug 21, 2020 at 16:19
  • @TJLuoma Bash at least doesn‘t complain
    – nohillside
    Commented Aug 21, 2020 at 16:28
  • I think it has something to do with globbing -- and I think there's a setting for zsh which would make it not complain. Anyway, if someone reads this in the future and it doesn't work, try putting a \ in front of the !
    – TJ Luoma
    Commented Aug 24, 2020 at 6:18
  • @TJLuoma In zsh it's probably possible without find :-). In bash one can use !(pattern-list) to exclude patterns, ! also starts history substitution unless followed by a space (so a lonesome ! usually is ok).
    – nohillside
    Commented Aug 24, 2020 at 6:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .