Find numbered subdirectories below number X and delete them

42 Views Asked by At

I have a folder 'masterfolder' that has subfolders with a numbered naming scheme:

\masterfolder\S01 \masterfolder\S02 \masterfolder\S03 \masterfolder\S04 \masterfolder\S05

Now I want to find and delete all folders below a specific number, for example S03. This means, S03, S04, S05 etc should not get deleted, S01 and S02 should get deleted.

I normally use this command to find and delete a specific folder:

find "/mnt/USBDRIVE/masterfolder" -type d -name "S02" -exec rm -rf '{}' \;

I tried finding a solution myself, but the only method I have found is to delete everything except the number I know I want to keep:

find "/mnt/USBDRIVE/masterfolder" -mindepth 1 -maxdepth 1 -type d -not -name "S03" -exec rm -rf '{}' \;

This will keep S03, but delete all others. I want to keep S03 and any other folder with a higher number than S03.

Any ideas appreciated.

1

There are 1 best solutions below

4
On

There are many ways to solve this.

Since your numbers are zero padded, the easiest way is to just send a list of the directories to a file sorted alphabetically. Then delete the ones you want ignored (they'll all be together), do a global change to add "rm " to the beginning of each line, and run the file as a script.

This will take you less than 30 seconds. Any programmatic solution will take longer.