击。删除所有文件和目录,但某些 [英] Bash. Delete all files and directories but certain ones
问题描述
我已经尝试过:
ls * grep -v mysql | grep -v temp | xargs rm -rf
但是这也保留了所有的名称中有mysql的文件,不需要它也不会删除任何其他目录。
任何想法?
您可以尝试:
rm -rf!(mysql | init)
哪个是 POSIX定义:
Glob模式还可以包含模式列表。模式列表是由两个|分隔的一个或多个模式的序列
或& amp; ...以下列表
描述有效的子模式。
...
!(pattern-list):
匹配与指定的模式列表不匹配的任何字符串。
...
注意:请花时间先测试一下!创建一些测试文件夹,或者简单地 echo
参数替换,正如@mnagel所述:
echo!(mysql | init)
添加有用信息 :如果匹配不是活动,您可以使用以下方式启用/禁用它:
shopt extglob#显示extglob状态
shopt -s extglob#启用extglob
shopt -u extglob#禁用extglob
I'm writing a script that needs to erase everything from a directory except two directories, mysql and 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.
any ideas?
You may try:
rm -rf !(mysql|init)
Which is POSIX defined:
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 !(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
这篇关于击。删除所有文件和目录,但某些的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!