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

Advertisements

4 Responses to Bash extended pattern matching

  1. doru001 says:

    Thank you, I finally got it!

  2. doru001 says:

    $ 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

    • doru001 says:

      $ echo ab!(c)!(d)e
      abcde

      • doru001 says:

        !(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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: