How to delete group of folders based on name and date

centosshell-script

I have a folder structure like this.

folders
    test1
    test2.1
    test49.85
    test4.95.89
    sample
    support
    util

These are all folders. I need to delete all folders that begin with test, except the most recent one. I do have access to the folder name of the most recent ${newestTestFolder} also.

Best Answer

Using extglob in Bash:

$ ls -1
sample
support
test1
test2.1
test4.95.89
test49.85
util
$ newestTestFolder="test49.85"
$ shopt -s extglob
$ ls -d1 !(@(${newestTestFolder}|!(test*)))
test1
test2.1
test4.95.89

This shows that

$ rm -r !(@(${newestTestFolder}|!(test*)))

does what you want in a single command all within Bash (with extglob enabled) - no extra process invocations (well, rm).

The pattern is explained in the Bash manual and means

  • !() - not the pattern within
  • @() - one of the patterns within
  • | - separates patterns