tl; dr
find ./myfolder -mindepth 1 -maxdepth 1 -type d -not -name test2 \
-exec echo rm -rf '{}' \;
Loại bỏ tiếng vang nếu hài lòng với danh sách các tập tin.
Sử dụng -mindepth 1sẽ đảm bảo rằng thư mục trên cùng không được chọn.
$ find ./myfolder -mindepth 1 -type d
./myfolder/test2
./myfolder/test2/one
./myfolder/test2/two
./myfolder/test
./myfolder/test/a1
./myfolder/test/a1/a2
./myfolder/test/a1/a2/a3
Nhưng -not -name test2sẽ không tránh được các thư mục con bên trong test2:
$ find ./myfolder -mindepth 1 -type d -not -name 'test2'
./myfolder/test2/one
./myfolder/test2/two
./myfolder/test
./myfolder/test/a1
./myfolder/test/a1/a2
./myfolder/test/a1/a2/a3
Để làm điều đó, bạn cần một cái gì đó như tỉa:
$ find ./myfolder -mindepth 1 -name test2 -prune -o -type d -print
./myfolder/test
./myfolder/test/a1
./myfolder/test/a1/a2
./myfolder/test/a1/a2/a3
Nhưng không sử dụng delete, vì nó ngụ ý depthvà điều đó sẽ bắt đầu xóa khỏi con đường dài nhất:
$ find ./myfolder -depth -mindepth 1 -name test2 -prune -o -type d -print
./myfolder/test/a1/a2/a3
./myfolder/test/a1/a2
./myfolder/test/a1
./myfolder/test
Sử dụng rm -rf(loại bỏ echonếu bạn muốn thực sự xóa):
$ find ./myfolder -mindepth 1 -name test2 -prune -o -type d -exec echo rm -rf '{}' \;
rm -rf ./myfolder/test
rm -rf ./myfolder/test/a1
rm -rf ./myfolder/test/a1/a2
rm -rf ./myfolder/test/a1/a2/a3
Hoặc, cũng sử dụng maxdepthnếu tất cả những gì bạn cần là xóa các thư mục (và mọi thứ bên trong) (xóa cái echođể thực sự xóa):
$ find ./myfolder -mindepth 1 -maxdepth 1 -type d -not -name test2 -exec echo rm -rf '{}' \;
rm -rf ./myfolder/test
A -deletevẫn sẽ thất bại nếu thư mục không trống:
$ find ./myfolder -mindepth 1 -maxdepth 1 -type d -not -name test2 -delete
find: cannot delete ‘./myfolder/test’: Directory not empty