Bash – Delete folders which not match a list

bashshell-script

I need practical example how get rid folders which are not in the list in Linux.
So i do not need to compare its contents or md5sums, just compare folders names.

For example, one folder has few folders inside

target_folder/
├── folder1
├── folder2
├── folder3
└── folder4

and my folders name list is txt file, includes folder1, folder2 and not folder3 and folder4.

How to remove folder3 and folder4 via bash script?

This has been answered on serverfault as

GLOBIGNORE=folder1:folder2
rm -r *
uset GLOBIGNORE

but my real task to delete bunch of folders. The txt list contains around 100 folders and target folder to clean is 200 folders.

Note that this should work both in Linux and FreeBSD.

EDIT:
target_folder may contain folders with sub-folders and also files. No spaces and leading dots and names are not similar: foo.com bar.org emptydir file.txt simplefile. But all these items should be deleted except those names in the list.

First answer is more obvious and simple. Second one more advanced and flexible, it allows you to delete based on item type as well.

Best Answer

Assuming your file names do not contain any of :\[*?, you could still use GLOBIGNORE. Just format your list of directories accordingly. For example:

$ cat names.txt
folder1
folder3

That is very easy to transform into a colon separated list:

$ paste -s -d : names.txt
folder1:folder3

So, you can now set that as the value of GLOBIGNORE:

GLOBIGNORE=$(paste -s -d : ../names.txt)

And proceed to delete them normally:

rm -r -- *

I just tested this on Linux with 300 directories and it worked perfectly.

Related Question