Bash extended pattern matching

Sun, 2008-09-14

If you don’t have extended pattern matching enabled you can enable it with shopt -s extglob

From the bash manual page:

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 fol‐
lowing 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

Example:

$ touch abc1d abc2d abcd abc11d abc3d
$ ls
abc11d abc1d abc2d abc3d abcd
$ ls abc?(1|2)d
abc1d abc2d abcd
$ ls abc*(1|2)d
abc11d abc1d abc2d abcd
$ ls abc+(1|2)d
abc11d abc1d abc2d
$ ls abc@(1|2)d
abc1d abc2d
$ ls abc!(1|2)d
abc11d abc3d abcd