Mic*_*ott 16 linux terminal command-line macos
我可以使用以下内容删除目标目录并递归地删除其所有子目录和内容。
find '/target/directory/' -type d -name '*' -print0 | xargs -0 rm -rf
Run Code Online (Sandbox Code Playgroud)
但是,我不希望删除目标目录。如何仅删除目标中的文件、子目录及其内容?
小智 14
之前的答案几乎是正确的。但是,如果您希望它们工作,则不应引用shell glob 字符。所以,这是您正在寻找的命令:
rm -rf "/target/directory with spaces/"*
Run Code Online (Sandbox Code Playgroud)
请注意,* 在双引号之外。这种形式也适用:
rm -rf /target/directory\ with\ spaces/*
Run Code Online (Sandbox Code Playgroud)
如果你*有如上所示的引号,那么它只会尝试删除*在目标目录中按字面命名的单个文件。
还有三个选项。
find与-mindepth 1和 一起使用-delete:
?mindepth 级别
不要在低于级别(非负整数)的级别上应用任何测试或操作。
?mindepth 1 表示处理除命令行参数之外的所有文件。-delete
删除文件;如果删除成功,则为 true。如果删除失败,则会发出错误消息。如果 ?delete 失败,find 的退出状态将为非零(当它最终退出时)。使用 ?delete 会自动打开 ?depth 选项。
在使用此选项之前,请仔细使用 -depth 选项进行测试。
# optimal?
# -xdev don't follow links to other filesystems
find '/target/dir with spaces/' -xdev -mindepth 1 -delete
# Sergey's version
# -xdev don't follow links to other filesystems
# -depth process depth-first not breadth-first
find '/target/dir with spaces/' -xdev -depth -mindepth1 -exec rm -rf {} \;
Run Code Online (Sandbox Code Playgroud)
2. 使用find, 但与文件,而不是目录。这避免了需要rm -rf:
# delete all the files;
find '/target/dir with spaces/' -type f -exec rm {} \;
# then get all the dirs but parent
find '/target/dir with spaces/' -mindepth 1 -depth -type d -exec rmdir {} \;
# near-equivalent, slightly easier for new users to remember
find '/target/dir with spaces/' -type f -print0 | xargs -0 rm
find '/target/dir with spaces/' -mindepth 1 -depth -type d -print0 | xargs -0 rmdir
Run Code Online (Sandbox Code Playgroud)
3. 继续删除父目录,但重新创建它。您可以创建一个 bash 函数来使用一个命令执行此操作;这是一个简单的单行:
rm -rf '/target/dir with spaces' ; mkdir '/target/dir with spaces'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
77035 次 |
| 最近记录: |