使用 Bash 删除除某些文件和目录之外的所有文件和目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17959317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Delete all files and directories but certain ones using Bash
提问by Bobo
I'm writing a script that needs to erase everything from a directory except two directories, mysql and temp.
我正在编写一个脚本,该脚本需要从目录中删除除两个目录 mysql 和 temp 之外的所有内容。
I've tried this:
我试过这个:
ls * | grep -v mysql | grep -v temp | xargs rm -rf
but this also keeps all the files that have mysql in their name, that i don't need. it also doesn't delete any other directories.
但这也保留了我不需要的所有名称中包含 mysql 的文件。它也不会删除任何其他目录。
any ideas?
有任何想法吗?
回答by Rubens
You may try:
你可以试试:
rm -rf !(mysql|init)
Which is POSIX defined:
这是POSIX 定义的:
Glob patterns can also contain pattern lists. A pattern list is a sequence
of one or more patterns separated by either | or &. ... The following list
describes valid sub-patterns.
...
!(pattern-list):
Matches any string that does not match the specified pattern-list.
...
Note: Please, take time to test it first! Either create some test folder, or simply echo
the parameter substitution, as duly noted by @mnagel:
注意:请先花时间测试一下!要么创建一些测试文件夹,要么只是echo
参数替换,正如@mnagel 所指出的:
echo !(mysql|init)
Adding useful information: if the matching is not active, you may to enable/disable it by using:
添加有用的信息:如果匹配不是活动的,您可以使用以下方法启用/禁用它:
shopt extglob # shows extglob status
shopt -s extglob # enables extglob
shopt -u extglob # disables extglob
回答by chrylis -cautiouslyoptimistic-
This is usually a job for find
. Try the following command (add -rf
if you need a recursive delete):
这通常是find
. 尝试以下命令(-rf
如果需要递归删除,请添加):
find . -maxdepth 1 \! \( -name mysql -o -name temp \) -exec rm '{}' \;
(That is, find entries in .
but not subdirectories that are not [named mysql
or named tmp
] and call rm
on them.)
(也就是说,在.
不是 [namedmysql
或 named tmp
] 的子目录中查找条目并调用rm
它们。)
回答by AlienHoboken
You can use find, ignore mysql and temp, and then rm -rf them.
您可以使用 find,忽略 mysql 和 temp,然后 rm -rf 它们。
find . ! -iname mysql ! -iname temp -exec rm -rf {} \;