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]matchesa,b, orc. - 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-ora).
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}: Exactlynoccurrences.{n,m}: Betweennandmoccurrences.
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:
-
grepwith extended regex: -
Conditional checks:
-
sedfor substitution:
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[[ ... =~ ... ]].