Python Pattern Matching: Regex & Extended Globs
Pattern matching in Bash operates on two distinct engines: Shell Pathname Expansion (Globbing like `*.txt`, `[0-9]`, `{a,b}`) and Regular Expressions (Regex like `^`, `$`, `[a-z]+`, `(foo|bar)`). Mastering both empowers advanced filtering and file manipulation.
"Globs are wide fishing nets designed to scoop up files by name; Regexes are precision surgical scalpels designed to match detailed string patterns inside text."
Deep Dive: How It Works
Basic vs Extended Regex: BRE (`grep`) requires escaping special chars like `\(`, `\)`, `\+`; ERE (`grep -E` or `egrep`) supports raw `+`, `?`, `|`, `()` directly.
Regex Anchors: `^` matches start of line, `$` matches end of line, `\b` matches word boundary.
Bash extglob: `shopt -s extglob` enables `?()`, `*()`, `+()`, `@()`, and `!()` inverse globs.
Syntax Blueprint
grep -E "^[0-9]{4}-[0-9]{2}-[0-9]{2}" log.txt # ISO date at line start
grep -E "(ERROR|FATAL|PANIC)" app.log # Multiple keywordsUse grep -E with anchors and quantifier groups for advanced pattern matching.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Using unquoted regex metacharacters like `*` or `?` directly in shell commands.Why it happens: Bash expands globs before passing arguments to the command.
How to fix: Always wrap regex patterns in single quotes: `grep -E '^[a-z]+'`.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Match Lines Starting with Numbers
Create `/tmp/regex_test.txt` with lines "123 Main St", "First Ave", and "456 Oak Rd".
Use `grep -E "^[0-9]+"` to output lines starting with numbers.
Delete the temporary file.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.