The glob

suggest change

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

If there is a need to match specific characters then ‘[]’ can be used. Any character inside ‘[]’ will be matched exactly once.

$ echo [m]acy
macy
$ echo [st][tr]acy
stacy tracy

The [] glob, however, is more versatile than just that. It also allows for a negative match and even matching ranges of characters and characterclasses. A negative match is achieved by using \! or ^ as the first character following \[. We can match stacy by

$ echo [!t][^r]acy
stacy

Here we are telling bash the we want to match only files which do not not start with a t and the second letter is not an r and the file ends in acy.

Ranges can be matched by seperating a pair of characters with a hyphen (\-). Any character that falls between those two enclosing characters - inclusive - will be matched. E.g., [r-t] is equivalent to [rst]

$ echo [r-t][r-t]acy
stacy tracy

Character classes can be matched by [:class:], e.g., in order to match files that contain a whitespace

$ echo *[[:blank:]]*
file with space

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents