Pattern matching and regular expressions

suggest change

Syntax

Remarks

Character Classes

Valid character classes for the [] glob are defined by the POSIX standard:

alnum alpha ascii blank cntrl digit graph lower print punct space upper word xdigit

Inside [] more than one character class or range can be used, e.g.,

$ echo a[a-z[:blank:]0-9]*

will match any file that starts with an a and is followed by either a lowercase letter or a blank or a digit.

It should be kept in mind, though, that a [] glob can only be wholly negated and not only parts of it. The negating character must be the first character following the opening \[, e.g., this expression matches all files that do not start with an a

$ echo [^a]*

The following matches every name that starts with a letter, a ^, or an a

$ echo [[:alpha:]^a]*

It does not mean “any letter except a”, because the ^ is interpreted as a literal ^ unless it is the first character of the class.

Escaping glob characters

It is possible that a file or folder contains a glob character as part of its name. In this case a glob can be escaped with a preceding \\ in order for a literal match. Another approach is to use double "" or single '' quotes to address the file. Bash does not process globs that are enclosed within "" or ''.

Difference to Regular Expressions

The most significant difference between globs and regular expressions is that a regular expression needs both something to match and a quantifier. A glob’s * already means “any string”; the equivalent regular expression is .*, where . is any character and * means zero or more of the previous atom. The equivalent regular expression for the ? glob is .{1} (any one character), not the ? quantifier, which means zero or one. A [] class can be used in a regular expression as well, but it still needs a quantifier if you want to repeat it.

Equivalent Regular Expressions

Glob Regular expression
* .*
? .
[] []

Feedback about page:

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



Table Of Contents