Extended Pattern Matching

Bash provides a further set of pattern matching operators if the shopt option extglob is switched on. Each operator takes one or more patterns, normally strings, separated by the vertical bar ( | ). The extended pattern matching operators are given in Table 4-3.[8]

Table 4-3. Pattern-matching operators

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元

Operator

Meaning

*(patternlist)

Matches zero or more occurrences of the given patterns.

+(patternlist)

Matches one or more occurrences of the given patterns.

?(patternlist)

Matches zero or one occurrences of the given patterns.

@(patternlist)

Matches exactly one of the given patterns.

!(patternlist)

Matches anything except one of the given patterns.

Some examples of these include:

 

 
  • *(alice|hatter|hare) would match zero or more occurrences of alice, hatter, and hare. So it would match the null string, alice, alicehatter, etc.
  • +(alice|hatter|hare) would do the same except not match the null string.
  • ?(alice|hatter|hare) would only match the null string, alice, hatter, or hare.
  • @(alice|hatter|hare) would only match alice, hatter, or hare.
  • !(alice|hatter|hare) matches everything except alice, hatter, and hare.

The values provided can contain shell wildcards too. So, for example, +([0-9]) matches a number of one or more digits. The patterns can also be nested, so you could remove all files except those beginning with vt followed by a number by doing rm !(vt+([0-9])).

 


[4] The colon (:) in all but the last of these operators is actually optional. If the colon is omitted, then change "exists and isn't null" to "exists" in each definition, i.e., the operator tests for existence only.

[7] PCX is a popular graphics file format under Microsoft Windows. JPEG (Joint Photographic Expert Group) is a common graphics format on the Internet and is used to a great extent on web pages.

[8] Be aware that these are not available in early releases of bash 2.0.