Joe*_*aad 8 filesystem directory directory-structure
我想删除目录 B 和 D。但我想保留 C 及其所有后代文件和目录。除一个目录及其子目录外,删除父目录的所有子目录的命令是什么。
帮助表示赞赏。
使用 bash shell 的扩展 glob功能(在当前的 Ubuntu 安装中默认启用),给定
$ tree A
A
??? B
??? C
? ??? ac1
? ??? ac2
??? D
5 directories, 0 files
Run Code Online (Sandbox Code Playgroud)
您可以C使用 glob 表达式来解决所有排除及其内容的问题,A/!(C)即
$ echo A/!(C)
A/B A/D
Run Code Online (Sandbox Code Playgroud)
因此,要删除除目录C及其内容之外的所有内容,您可以简单地使用
rm -rf A/!(C)
Run Code Online (Sandbox Code Playgroud)
离开
$ tree A
A
??? C
??? ac1
??? ac2
3 directories, 0 files
Run Code Online (Sandbox Code Playgroud)
你想要的是这个命令:
find ~/TESTDIR -mindepth 1 -maxdepth 1 -type d -not \( -name "keepMe" \) -exec rm -rf {} \;
Run Code Online (Sandbox Code Playgroud)
# List what's inside directory we want to remove
$ ls
file1 file2 keepMe/ removeA/ removeB/
??Testing what find gives without removing
$ find ~/TESTDIR -mindepth 1 -type d -not \( -name "keepMe" \)
/home/xieerqi/TESTDIR/removeA
/home/xieerqi/TESTDIR/removeB
# Actual removal and testls
$ find ~/TESTDIR -mindepth 1 -maxdepth 1 -type d -not \( -name "keepMe" \) -exec rm -rf {} \;
$ ls
file1 file2 keepMe/
Run Code Online (Sandbox Code Playgroud)
find DIRECTORY 调用 find 命令对 DIRECTORY 进行操作-mindepth 1 : 只处理目录的内容,避免目录本身是 0 级-maxdepth 1: 防止下降到子目录(rm -rf无论如何都是递归的,所以我们不需要下降到子目录来删除它们)-type d : 只搜索目录-not \( -name "keepMe" \) 忽略具有您要保留的名称的项目-exec rm -rf {} \; 对每个找到的项目执行删除一种简单的方法是使用trash-cli
你可以安装它 sudo apt-get install trash-cli
安装后,您可以导航到父目录 A,cd /A然后发出命令
trash B D,其中 B 和 D 是您要删除的目录(它们最终会出现在它们所在驱动器的垃圾箱中,因此如果您犯了错误,您可以恢复文件)
在 Ubuntu 16.04 和 14.04 下测试