Skip to content

Pattern Matching

Pattern Matching Basics

Regular expressions (regex) are a powerful tool for matching patterns in text, enabling tasks like searching, replacing, and validating strings. In BASH scripting, regex is integral to utilities like grep, sed, and conditional checks using [[ ... =~ ... ]]. This section introduces core regex syntax, including metacharacters, character classes, and quantifiers.


Metacharacters and Special Symbols

Metacharacters define patterns that match specific types of text. Common ones include:

  • . (dot): Matches any single character (except a newline).
  • * (asterisk): Matches zero or more of the preceding element.
  • + (plus): Matches one or more of the preceding element.
  • ? (question mark): Matches zero or one of the preceding element.
  • ^ (caret): Anchors the pattern to the start of a string.
  • $ (dollar): Anchors the pattern to the end of a string.

Example:

echo "apple" | grep -E 'a.pple'  # Matches "apple" (a . p p l e)
echo "banana" | grep -E 'b.n'   # Matches "banana" (b . n)


Character Classes

Character classes define a set of allowed characters using square brackets []. They are useful for matching any one of several characters.

  • Literal characters: [abc] matches a, b, or c.
  • Ranges: [a-z] matches any lowercase letter; [0-9] matches any digit.
  • Special characters: Escape ] or - if they appear in the class (e.g., [-a] matches - or a).

Example:

echo "color" | grep -E '[aeiou]'  # Matches "color" (contains vowels)
echo "123" | grep -E '[0-9]+'    # Matches "12, 23, etc." (digits)


Quantifiers

Quantifiers specify how many times a character or group should appear:

  • *: Zero or more occurrences.
  • +: One or more occurrences.
  • ?: Zero or one occurrence.
  • {n}: Exactly n occurrences.
  • {n,m}: Between n and m occurrences.

Example:

echo "aaa" | grep -E 'a{3}'       # Matches "aaa" (exactly 3 a's)
echo "abbbc" | grep -E 'b{2,3}'   # Matches "abbbc" (2–3 b's)


Practical Examples with BASH Tools

Regex is often used with BASH utilities. Here are examples:

  1. grep with extended regex:

    grep -E '^[0-9]{3}-[0-9]{2}-[0-9]{4}$' data.txt  # Match dates like 123-45-6789
    

  2. Conditional checks:

    if [[ "hello123" =~ [a-z]+[0-9]+ ]]; then
      echo "Matched pattern"
    fi
    

  3. sed for substitution:

    echo "Price: $100" | sed 's/\$[0-9]\+/\$50/'  # Replace $100 with $50
    


Key takeaways

  • Metacharacters like . and * define flexible patterns for text matching.
  • Character classes ([abc] or [0-9]) allow matching any one of several characters.
  • Quantifiers (+, {3}) specify how many times a pattern should repeat.
  • Regex is essential for text processing in BASH, used with tools like grep, sed, and [[ ... =~ ... ]].