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