我原本认为
rm -r *.xml
会删除父文件夹和子文件夹中的所有文件,但:
*.xml: No such file or directory
rm 的 man 手册上写道:
-r, -R, --recursive
remove directories and their contents recursively
这意味着标志-r
需要一个目录作为参数,而*.xml
并不是一个目录。
如果想要递归地从当前目录中删除所有.xml文件,请使用以下命令:find . -name "*.xml" -type f|xargs rm -f
我假设您想要递归地删除所有*.xml
文件(包括当前目录和所有子目录)。为此,请使用find
命令:
find . -name "*.xml" -exec rm {} \;
顺便说一下,递归删除让我感到害怕。在我头脑清醒的日子里,我倾向于在此步骤之前进行如下操作:
find . -name "*.xml"
在执行删除操作前,可以先试着运行一遍命令 -exec
不包含在内,这样可以查看将会被删除的内容。我建议你也这么做,这样你的文件会感谢你的。
{}
- 原始版本没问题 - 可能是提问者打错了。 - Paul R阅读这篇有关在Unix中查找空目录的答案,我刚学会了-delete操作:
-delete
Delete files; true if removal succeeded. If the removal failed, an error message is issued. If -delete fails, find's exit status will be nonzero (when it even‐
tually exits). Use of -delete automatically turns on the -depth option.
Warnings: Don't forget that the find command line is evaluated as an expression, so putting -delete first will make find try to delete everything below the start‐
ing points you specified. When testing a find command line that you later intend to use with -delete, you should explicitly specify -depth in order to avoid
later surprises. Because -delete implies -depth, you cannot usefully use -prune and -delete together.
来源:man find
这意味着,您也可以像这样递归地删除所有xml文件:
find . -name "*.xml" -type f -delete
rm -rf */*.xml
更容易的了,所以我会选择我的答案,但是这是不被允许的 :D - holms还有一种更美观的方式,不过这种方式在Unix系统上得到的支持较少:
rm -rf */*.xml
ZSH递归通配符来解救!
启动zsh:
zsh
确保你在想要的目录中:
cd 任意位置
首先列出:
ls **/*.xml
删除:
rm **/*.xml
我将抵制强烈的诱惑,不去攻击bash,而只是指向相关的zsh文档主题这里。
一种简单的方法是
rm -f *.xml
这将从当前目录中删除所有 .xml 文件。
find -exec
。 - paulmelnikow-P
选项并行运行任务,则对于昂贵的操作,“xargs”可能会更有效率,但在这种情况下可能不会有太大的差异。然而,我同意@Rahul的看法,这取决于用户的喜好,可以说"find ... | xargs ..." 的语法比 "find .. -exec ... {} ;" 更容易记忆。(因此+1) - Shawn Chin