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 regexp

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

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

Regexp 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 

See also

Dialogue & Discussion