Bash extended pattern matching

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

4 thoughts on “Bash extended pattern matching

  1. $ touch abcde
    $ echo a+(b|c|d|e|f)e # iterates through a different letter every time
    abcde
    $ echo a+(b|e|f)!(c|d|e) # makes no sense
    abcde

      1. !(a|bd) means anything but a or bd. Anything as in *, anything at all. So !(c)!(d) fits cd, for example c is not “” and d is not cd, or c is not cd and d is not “”. A pretty complicated algorithm.

Leave a reply to doru001 Cancel reply