Yesterday, I need to remove all sub-directory excluding some directories. The solution I found is using find and xargs.

For example, I have some directories and want to remove all directories except directory name “4”:

find . -maxdepth 1 -mindepth 1 -type d -not -name '4' -print0 | xargs -0 -I {} rm -rf {}
find and remove directories exclude one directory

Another example, I have some directories and want to remove all directories except directories with names “1” and “4”:

find . -maxdepth 1 -mindepth 1 -type d -not \( -name '4' -or -name '1' \) -print0 | xargs -0 -I {} rm -rf {}
find and remove directories exclude some directories

Reference: 3 Ways to Delete All Files in a Directory Except One or Few Files with Extensions