繁体   English   中英

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

[英]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.

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