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](/blog/til-find-delete-all-sub-directories-exclude-some-directory/find-and-remove-directories-exclude-1.png)
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](/blog/til-find-delete-all-sub-directories-exclude-some-directory/find-and-remove-directories-exclude-2.png)
Reference: 3 Ways to Delete All Files in a Directory Except One or Few Files with Extensions