gpt4 book ai didi

linux - 删除除特定目录之外的所有目录

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:33:30 24 4
gpt4 key购买 nike

在 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]#

我调查了 How to exclude a directory in find . command并像这样尝试修剪开关

[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

关于linux - 删除除特定目录之外的所有目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53625221/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com