Bash 通配符可以指定否定匹配吗?

Bash 通配符可以指定否定匹配吗?

是否bash可以使用通配符来指定“当前目录中除 [与特定(通配符)模式匹配的文件] 之外的所有文件”?例如,“所有不匹配 *~ 的文件”

或者更一般地说,是否可以使用第二个过滤或否定规范来限定通配符文件规范?

答案1

当然。假设你想要所有文件名称中包含字符串“foo”,但没有包含“bar”的文件。所以你想要

foo1
foo2

但你不想

 foobar1

您可以使用简单的通配符来实现这一点,如下所示:

for f in foo!(bar)*; echo $f; done

或者

ls foo[^bar]*

更多内容请参见此处:http://www.tldp.org/LDP/abs/html/globbingref.html请注意,这两种方法都有缺陷。您最好使用find

答案2

感谢 bjanssen 指出 bashextglob shopt允许这种通配符。

来自bash手册页:

If the extglob shell option is enabled using the shopt builtin, several
extended pattern matching operators are recognized. In the following 
description, a pattern-list is a list of one or more patterns separated 
by a |.  Composite patterns may be formed using one or more of the following
sub-patterns:

          ?(pattern-list)
                 Matches zero or one occurrence of the given patterns
          *(pattern-list)
                 Matches zero or more occurrences of the given patterns
          +(pattern-list)
                 Matches one or more occurrences of the given patterns
          @(pattern-list)
                 Matches one of the given patterns
          !(pattern-list)
                 Matches anything except one of the given patterns

因此,回答我的问题“如何指定所有不匹配的文件 *~“ :

!(*~)

或者,无需extglob

*[^~]

更一般地,回答我的问题的最后部分:

The GLOBIGNORE shell variable may be used to restrict the set of file names
matching a pattern. If GLOBIGNORE is set, each matching file name that also
matches one of the (colon-separated) patterns in GLOBIGNORE is removed from
the list of matches.

相关内容