How to use grep with regular expressions
Match complex text patterns using basic and extended regular expressions with grep's -E and -P flags.
Match text patterns using regular expressions in grep, including character classes, quantifiers, alternation, and anchors with the
-E(extended) and-P(Perl) flags.
Step-by-Step: Use grep with Regular Expressions
1. Match Multiple Alternatives with grep Extended Regex
grep -E "error|warning|critical" /var/log/syslogThe grep
-E flag enables Extended Regular Expressions (ERE), which supports
| (alternation),
+ (one or more), and
? (zero or one) without backslash escaping.
2. Match a Pattern at the Start or End of a Line
grep "^server" /etc/nginx/nginx.conf
grep "\.log$" /etc/logrotate.d/nginxThe
^ anchor matches the start of a line. The
$ anchor matches the end. These are supported in both BRE and ERE modes.
3. Match IP Addresses with grep
grep -E "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" /var/log/auth.log4. Use Perl-Compatible Regex with grep
grep -P "\d{4}-\d{2}-\d{2}" /var/log/app.logThe grep
-P flag enables Perl-Compatible Regular Expressions (PCRE), which adds
\d (digit),
\w (word character), lookahead, and lookbehind.
Common Issues
"Invalid regular expression"— Special characters like
(,
),
{,
},
|, and
+ must be escaped in Basic Regular Expression (BRE) mode. Use
-E for extended regex where these characters work without escaping. See
grep: Invalid regular expression.