简体   繁体   中英

Delete all files and folders recursively but excluding one folder

I have a folder structure like this:

my-root-folder
├── .git
├── README.md
├── index.css
├── index.js
├── index.html
├── assets
│   ├── image
│   │   ├── logo.jpg
│   │   ├── header.jpg

i want delete all files and folder into my-root-folder but not the .git folder ( ./my-root-folder/.git ) and his child.

i have tried with this command, but always delete all:

shopt -s extglob && rm -rf ./* !(".git")

Side note i'm in a docker image based on alpine.

You can try with find :

find my-root-folder -mindepth 1 -not -path "*/.git*" -delete

Roughly translated, this means: find inside my-root-folder everything at least one level deep (so, exclude the folder itself) that does not match the predicate path contains "/.git" and delete it.

Note that the argument ".git" is actually a regular expression, so be careful when adapting to other situations. find is a very powerful and useful tool, so be sure to check out its documentation!

This find command delete nested .git as well :

find .  -mindepth 1 -path ./.git -prune -o -exec echo rm -rf {} \;

-path ./.git -prune -o excludes only top level .git

One drawback is you may see messages because find tries to access directories it has already deleted.

Remove echo once you are happy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM