使用Bash删除所有文件和目录,但某些文件和目录

时间:2013-07-30 23:43:00

标签: bash file ubuntu directory

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

我试过这个:

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

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

任何想法?

3 个答案:

答案 0 :(得分:27)

您可以尝试:

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

答案 1 :(得分:5)

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

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

(即查找.中的条目,但不查找未[名为mysql或名为tmp]的子目录,并在其上调用rm。)

答案 2 :(得分:3)

您可以使用find,ignore mysql和temp,然后使用rm -rf。

find . ! -iname mysql ! -iname temp -exec rm -rf {} \;