Bash Pattern matching and regular expressions Extended globbing


Example

2.02

Preparation

$ mkdir globbing
$ cd globbing
$ mkdir -p folder/{sub,another}folder/content/deepfolder/
touch macy stacy tracy "file with space" folder/{sub,another}folder/content/deepfolder/file .hiddenfile
$ shopt -u nullglob
$ shopt -u failglob
$ shopt -u dotglob
$ shopt -u nocaseglob
$ shopt -u extglob
$ shopt -u globstar

Bash's built-in extglob option can extend a glob's matching capabilities

shopt -s extglob

The following sub-patterns comprise valid extended globs:

  • ?(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

The pattern-list is a list of globs separated by |.

$ echo *([r-t])acy
stacy tracy

$ echo *([r-t]|m)acy
macy stacy tracy

$ echo ?([a-z])acy
macy

The pattern-list itself can be another, nested extended glob. In the above example we have seen that we can match tracy and stacy with *(r-t). This extended glob itself can be used inside the negated extended glob !(pattern-list) in order to match macy

$ echo !(*([r-t]))acy
macy

It matches anything that does not start with zero or more occurrences of the letters r, s and t, which leaves only macy as possible match.