sed -E Extended Regex for Cleaner Patterns
sed -E enables extended regular expressions, so quantifiers and groups need no backslash escaping.
Default sed uses basic regex where you must escape +, ?, |, and (). The -E flag turns on extended regex and makes complex patterns far more readable.
What it does
With basic regular expressions (the default), characters like + ? | ( ) { } are literal and must be backslash-escaped to act as metacharacters. The -E flag selects extended regular expressions where those characters are metacharacters by default.
Common usage
# BRE: escape the metacharacters
sed 's/\([0-9]\+\)/[\1]/' file
# ERE with -E: no backslashes needed
sed -E 's/([0-9]+)/[\1]/' file
sed -E 's/(cat|dog)/pet/' file
sed -E 's/colou?r/color/g' fileOptions
| Flag | What it does |
|---|---|
| -E | Use extended regex (POSIX, GNU and modern BSD) |
| -r | GNU synonym for -E (not on BSD) |
| + | One or more, unescaped under -E |
| ? | Optional, unescaped under -E |
| | | Alternation, unescaped under -E |
| ( ) | Grouping, unescaped under -E |
In CI
Use -E rather than -r in portable scripts: -E works on both GNU and BSD sed, while -r is GNU only and errors on macOS. GNU sed accepts -E as an alias for -r, so -E is the safe choice everywhere.
Common errors in CI
On macOS, sed -r 's/(a|b)/x/' raises sed: illegal option -- r. Forgetting you are in BRE mode gives a literal-match miss: s/[0-9]+/N/ without -E matches a digit followed by a literal plus sign, not one or more digits.