TL; DR
find ./myfolder -mindepth 1 -maxdepth 1 -type d -not -name test2 \
-exec echo rm -rf '{}' \;
ลบเสียงก้องถ้าพอใจกับรายชื่อไฟล์
การใช้-mindepth 1จะทำให้แน่ใจว่าไม่ได้เลือกไดเรกทอรีบนสุด
$ 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
แต่-not -name test2จะไม่หลีกเลี่ยงตำบลภายใน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
ในการทำเช่นนั้นคุณต้องมีลูกพรุน:
$ 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
แต่อย่าใช้deleteเพราะมันหมายถึงdepthและจะเริ่มลบจากเส้นทางที่ยาวที่สุด:
$ 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
ใช้อย่างใดอย่างหนึ่งrm -rf(ลบechoหากคุณต้องการลบจริง):
$ 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
หรือยังใช้maxdepthถ้าทั้งหมดที่คุณต้องการก็คือการลบไดเรกทอรี (และภายในทุกอย่าง) (ลบechoจริงลบ):
$ find ./myfolder -mindepth 1 -maxdepth 1 -type d -not -name test2 -exec echo rm -rf '{}' \;
rm -rf ./myfolder/test
-deleteจะยังคงล้มเหลวถ้าไดเรกทอรีไม่ว่าง:
$ find ./myfolder -mindepth 1 -maxdepth 1 -type d -not -name test2 -delete
find: cannot delete ‘./myfolder/test’: Directory not empty