[英]Delete all directories excluding a specific one
On a linux host, given an absolute path, I want to delete all except a certain directory.在linux主机上,给定绝对路径,我想删除除某个目录外的所有内容。 To simplify things below is the directory structure and I want to delete all directories except test2
为了简化下面的内容是目录结构,我想删除除 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]#
I looked into How to exclude a directory in find .我查看了如何在 find 中排除目录。 command and tried the prune switch like this
命令并尝试像这样修剪开关
[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]
now it lists all the folder including /opt/data/test and if I add the xargs rm -rf to this, it will delete the parent folder as well.现在它列出了包括 /opt/data/test 在内的所有文件夹,如果我将 xargs rm -rf 添加到其中,它也会删除父文件夹。 I don't think I understood the concept -path and -name correctly, please help
我认为我没有正确理解 -path 和 -name 的概念,请帮忙
Using a simple negation with -not
may be easier than pruning:使用带有
-not
的简单否定可能比修剪更容易:
$ find /opt/data/test -type d -not -name test2
EDIT:编辑:
There's no reason to recurse in to the subdirectories, since you're going to delete the top directories anyway, so you could add -maxdepth
and avoid finding the directories inside 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.