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"
fi

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"
fi

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 [[ "foo123.zip" =~ [[:digit:]]+\.zip$ ]]; then
    echo "matches"
else
    echo "does not match"
fi 

Dialogue & Discussion