Bash Regular Expressions: Reference and Examples

Last updated:
Table of Contents

WIP Alert This is a work in progress. Current information is correct but more content may be added in the future.

String matches regex

Use "<str>"=~ <regex>:

Example string starts with f

if [[ "foo" =~ ^f ]]; then
 echo "match"

OR operator

To match one pattern OR another, use parentheses: (pattern_1|pattern_2)

Example string begins with f or ends with o:

if [[ "foo" =~ (^f|o$) ]]; then
 echo "match"

Regex with character classes

Other character classes include: "alnum", "alpha", "ascii", "blank", "lower", "punct", "space", "upper", "word", etc

Example: file whose name ends in a number plus the extension .zip:

# prints "matches"
if [[ "" =~ [[:digit:]]+\.zip$ ]]; then
    echo "matches"
    echo "does not match"

Dialogue & Discussion