我正在编写一个脚本,它需要从一个目录中删除除两个目录(mysql 和 temp)之外的所有内容。
我已经试过了:
ls * | grep -v mysql | grep -v temp | xargs rm -rf
但这也保留了所有我不需要的名称中包含 mysql 的文件。它也不会删除任何其他目录。
有什么想法吗?
最佳答案
你可以试试:
rm -rf !(mysql|init)
这是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.
...
注意:请先花时间测试一下!要么创建一些测试文件夹,要么简单地 echo
参数替换,正如@mnagel 所指出的那样:
echo !(mysql|init)
Adding useful information : 如果匹配未激活,您可以使用以下方式启用/禁用它:
shopt extglob # shows extglob status
shopt -s extglob # enables extglob
shopt -u extglob # disables extglob
关于bash - 使用 Bash 删除除某些文件和目录之外的所有文件和目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17959317/