使用Bash删除所有文件和目录,但删除某些文件和目录 [英] Delete all files and directories but certain ones using Bash

查看:99
本文介绍了使用Bash删除所有文件和目录,但删除某些文件和目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个脚本,该脚本需要删除目录中除mysql和temp这两个目录以外的所有内容.

I'm writing a script that needs to erase everything from a directory except two directories, mysql and temp.

我已经尝试过了:

ls * | grep -v mysql | grep -v temp | xargs rm -rf

但是这也会保留我不需要的所有具有mysql名称的文件.它也不会删除任何其他目录.

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.

有什么想法吗?

推荐答案

您可以尝试:

rm -rf !(mysql|init)

定义了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.
...

注意:请花些时间先对其进行测试!如@mnagel所述,要么创建一些测试文件夹,要么简单地echo参数替换:

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)

添加有用的信息 :如果该匹配项不是 active ,则可以通过以下方式启用/禁用该匹配项:

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

这篇关于使用Bash删除所有文件和目录,但删除某些文件和目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆