[英]Delete all directories excluding a specific one
在linux主機上,給定絕對路徑,我想刪除除某個目錄外的所有內容。 為了簡化下面的內容是目錄結構,我想刪除除 test2 之外的所有目錄
[root@hostname test]# pwd
/opt/data/test
root@hostname test]# ls -ltr
total 8
drwxr-xr-x 5 root root 4096 Dec 5 09:33 test1
drwxr-xr-x 2 root root 4096 Dec 5 09:44 test2
[root@hostname test]#
我查看了如何在 find 中排除目錄。 命令並嘗試像這樣修剪開關
[root@hostname test]# find /opt/data/test -type d -path test2 -prune
-o ! -name "test2" -print
/opt/data/test
/opt/data/test/test1
/opt/data/test/test1/ls.txt
/opt/data/test/test1/test13
/opt/data/test/test1/test13/temp.py
/opt/data/test/test1/test13/try.pl
/opt/data/test/test1/test11
/opt/data/test/test1/test11/ls.txt
/opt/data/test/test1/test11/temp.py
/opt/data/test/test1/test11/try.pl
/opt/data/test/test1/test12
/opt/data/test/test1/test12/ls.txt
/opt/data/test/test1/test12/temp.py
/opt/data/test/test1/test12/try.pl
/opt/data/test/test1/temp.py
/opt/data/test/test1/try.pl
/opt/data/test/test2/ls.txt
/opt/data/test/test2/temp.py
/opt/data/test/test2/try.pl
[root@hostname test]
現在它列出了包括 /opt/data/test 在內的所有文件夾,如果我將 xargs rm -rf 添加到其中,它也會刪除父文件夾。 我認為我沒有正確理解 -path 和 -name 的概念,請幫忙
使用帶有-not
的簡單否定可能比修剪更容易:
$ find /opt/data/test -type d -not -name test2
編輯:
沒有理由遞歸到子目錄,因為無論如何你都會刪除頂級目錄,所以你可以添加-maxdepth
並避免在test2
找到目錄:
$ find /opt/data/test -maxdepth 1 -type d -not -name test2
通過將 -mindepth 1 添加到 find 命令以排除父目錄,我能夠實現所需的行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.