grep flags and regex reference
Complete reference for grep command-line flags, regular expression syntax, and character classes.
Complete reference for grep flags covering search modes, output control, context display, and regular expression syntax for BRE and ERE.
grep Search Mode Flags
| Flag | grep behavior | Default | Example |
|---|---|---|---|
-E | grep uses Extended Regular Expressions (ERE) — ` | ,+
,?
, ()
, {}` work without escaping | BRE |
-F | grep matches fixed strings — no regex interpretation, faster for literal patterns | BRE | `grep -F "error |
-P | grep uses Perl-Compatible Regular Expressions (PCRE) — adds
\d,
\w, lookahead, lookbehind | BRE | grep -P "\d{4}-\d{2}-\d{2}" log.txt |
-i | grep matches case-insensitively | Case-sensitive | grep -i "error" log.txt |
-w | grep matches whole words only — pattern must be bounded by non-word characters | Substring match | grep -w "error" log.txt (won't match "errors") |
-x | grep matches entire lines only — the pattern must match the complete line | Substring match | grep -x "exact line" file.txt |
grep Output Control Flags
| Flag | grep behavior | Default | Example |
|---|---|---|---|
-c | grep prints the count of matching lines instead of the lines themselves | Print lines | grep -c "error" log.txt |
-l | grep prints only filenames containing matches | Print lines | grep -rl "TODO" /project/ |
-L | grep prints only filenames NOT containing matches | Print lines | grep -rL "TODO" /project/ |
-n | grep prefixes each matching line with its line number | No numbers | grep -n "error" log.txt |
-v | grep inverts the match — prints lines that do NOT match the pattern | Normal match | grep -v "debug" log.txt |
-o | grep prints only the matched portion of each line, not the entire line | Full line | grep -oE "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+" access.log |
grep Context Flags
| Flag | grep behavior | Default | Example |
|---|---|---|---|
-A {n} | grep prints n lines AFTER each match for context | 0 | grep -A 3 "error" log.txt |
-B {n} | grep prints n lines BEFORE each match for context | 0 | grep -B 2 "error" log.txt |
-C {n} | grep prints n lines BEFORE and AFTER each match (combined context) | 0 | grep -C 5 "error" log.txt |
grep File Selection Flags
| Flag | grep behavior | Default | Example |
|---|---|---|---|
-r | grep searches all files in the directory tree recursively | Single file | grep -r "pattern" /etc/ |
--include=GLOB | grep searches only files matching the glob pattern during recursive search | All files | grep -r --include="*.conf" "listen" /etc/ |
--exclude=GLOB | grep skips files matching the glob pattern | None | grep -r --exclude="*.log" "pattern" /var/ |
-I | grep skips binary files during search | Process all | grep -rI "pattern" /var/log/ |