grep: Invalid regular expression
Diagnose and fix grep regex errors caused by unescaped special characters or BRE/ERE syntax confusion.
grep produces "Invalid regular expression" when the pattern contains syntax errors — typically unescaped special characters or ERE operators used in BRE mode.
What Causes This Error
grep uses Basic Regular Expressions (BRE) by default. In BRE, characters like
{,
},
(,
),
|, and
+ are literal unless escaped with backslashes. Using ERE syntax without the
-E flag triggers the "Invalid regular expression" error.
How to Fix
- Switch to Extended Regular Expressions with the
-Eflag:
grep -E "error|warning" /var/log/syslog- Or escape special characters in BRE mode:
grep "error\|warning" /var/log/syslog- For literal string matching (no regex), use
-F:
grep -F "error|warning" /var/log/syslogThe
-F flag treats the pattern as a fixed string —
| is matched literally.