15

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

我试过这个:

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

但这也保留了我不需要的所有名称中包含 mysql 的文件。它也不会删除任何其他目录。

有任何想法吗?

4

3 回答 3

35

你可以试试:

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.
...

注意:请花点时间先测试一下!要么创建一些测试文件夹,要么只是echo参数替换,正如@mnagel 正式指出的那样:

echo !(mysql|init)

添加有用信息:如果匹配未激活,您可以使用以下方法启用/禁用它:

shopt extglob                   # shows extglob status
shopt -s extglob                # enables extglob
shopt -u extglob                # disables extglob
于 2013-07-30T23:47:32.060 回答
5

这通常是find. 尝试以下命令(-rf如果需要递归删除,请添加):

find . -maxdepth 1 \! \( -name mysql -o -name temp \) -exec rm '{}' \;

(也就是说,在.非 [namedmysql或 named tmp] 的子目录中查找条目,然后调用rm它们。)

于 2013-07-30T23:53:45.293 回答
3

你可以使用find,忽略mysql和temp,然后rm -rf。

find . ! -iname mysql ! -iname temp -exec rm -rf {} \;
于 2013-07-30T23:51:29.597 回答