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

  1. Switch to Extended Regular Expressions with the -E flag:
grep -E "error|warning" /var/log/syslog
  1. Or escape special characters in BRE mode:
grep "error\|warning" /var/log/syslog
  1. For literal string matching (no regex), use -F:
grep -F "error|warning" /var/log/syslog

The -F flag treats the pattern as a fixed string — | is matched literally.