grep 'pattern' file prints every line of file that matches pattern. This cheat sheet covers the flags and recipes I use daily: case-insensitive (-i), whole-word (-w), inverted (-v), multiple patterns, recursive search, counting lines versus occurrences, unique counts, printing a column with awk, and the BRE, ERE and PCRE regex modes, each with the macOS BSD and PowerShell variant, plus when to reach for ripgrep or ag instead.
The flag set is small but the gotchas are not: macOS ships BSD grep without -P (PCRE), it accepts regex shortcuts like \d that GNU grep does not, recursive search treats symlinks differently, and several flags you reach for on Linux are missing or different on older BSD builds. Every command below rewrites itself for the platform you pick.
What is grep used for?
grep is used to search text for lines that match a pattern. grep reads one or more files, or the output of another command through a pipe, and prints every line that matches a regular expression or a fixed string. The everyday jobs are pulling errors out of log files, finding where a function or setting appears across a source tree, and filtering long command output.
Here is the smallest useful search, against a log file:
grep 'error' app.log2026-11-24 09:14:02 error: connection refused (db-primary:5432)
2026-11-24 09:14:07 error: retry 1 of 3 failed
Each output line is a whole matching line from the file. Add -n to prefix line numbers, -i to catch Error and ERROR as well, and -r with a directory instead of a file to search a whole tree. On Windows, PowerShell's Select-String is the closest equivalent; the older findstr works in cmd.exe but has only a limited regex subset.
Set your OS, the text to search for, and the path. Every command on this page rewrites itself with your values.
grep by task (jump table)
Skim by intent. Each row links to the section on this page, or to the dedicated deep-dive article for that task.
| I want to... | Where |
|---|---|
| Search a file for a string | Basic search |
| Ignore case | Case-insensitive grep |
| Match a whole word, not a substring | Match a whole word |
| Search several patterns at once (OR, AND) | Search multiple patterns |
| Exclude lines that match (invert) | Exclude matching lines |
| Search a whole directory tree | Recursive search + deep dive |
| Exclude files or directories | Filtering by filename + deep dive |
| Show lines before and after a match | Context lines + deep dive |
| List only the filenames that match | List only filenames |
| Count how many matches | Count matches with grep |
| Count unique matches / rank them | Count unique matches |
| Extract a column from matching lines | grep and print a column |
| Understand BRE vs ERE vs PCRE | grep regex: BRE vs ERE vs PCRE |
| Choose between grep, ripgrep, and ag | grep vs ripgrep vs ag |
| Handle the macOS BSD vs GNU differences | macOS BSD vs GNU grep |
Basic search
Find a literal string in a file.
grep ':pattern' app.logSearch standard input (the most common pipeline use):
journalctl -u nginx | grep '500'Quote your patterns with single quotes, always, even when they look like plain words today, because the next edit might add a * or a $ that the shell would otherwise expand.
Common flags
The flags I reach for daily.
| Flag | Meaning |
|---|---|
-i | Case-insensitive |
-v | Invert match (lines that do NOT match) |
-c | Count matching lines per file |
-l | List filenames with matches (no line output) |
-L | List filenames WITHOUT matches |
-n | Prefix each line with its line number |
-H | Print filename with each match (default when searching multiple files) |
-h | Suppress filename prefix |
-w | Match whole words only |
-x | Match whole lines only |
-o | Print only the matched part, not the whole line |
-q | Quiet; exit status only (handy in if tests) |
-e | Add a pattern (repeatable) |
-f FILE | Read patterns from a file, one per line |
-E | Extended regex (ERE) |
-F | Fixed strings (no regex; safer when matching ., *, etc.) |
-P | Perl-compatible regex (GNU only) |
-r / -R | Recursive (GNU -R follows symlinks; macOS needs -S) |
-I | Skip binary files (capital i, unrelated to -i) |
-F is underused. If the pattern is a literal string with regex metacharacters in it, -F is faster and avoids escaping.
grep -F '192.168.1.1' access.logIn scripts, GNU grep returns 0 when a line matches, 1 when nothing matches, and 2 on an error. A no-match result is not a broken command. With -q, a match can produce status 0 even if an error also occurred. See GNU grep's exit status reference.
Case-insensitive grep
grep -i 'pattern' file matches regardless of case, so error, Error, ERROR, and eRRoR all hit. The flag is short for --ignore-case and works in every regex mode (grep, -E, -F, -P).
grep -i ':pattern' app.logThe PowerShell line has no extra flag because Select-String is case-insensitive by default, the opposite of grep. To make it case-sensitive you add -CaseSensitive.
-i stacks with everything else. The combinations I type most:
grep -rin -- ':pattern' ':search_path'grep -Fin -e 'error.code' app.log # literal text, any case (the dot is not a wildcard)
grep -in -e 'error' -e 'warning' app.log # any of several patterns, any case
grep -ic 'error' app.log # count matching lines, any case
grep -io 'error' app.log | wc -l # count every occurrence, any caseFor recursive PowerShell searches, pipe Get-ChildItem -Recurse -File into Select-String; Select-String itself has no -Recurse parameter. See Microsoft's Select-String reference.
The locale and UTF-8 caveat
-i reliably folds ASCII case only. Outside A-Z, case folding depends on your locale (LC_ALL, LC_CTYPE, LANG; check with locale). Under the C or POSIX locale, common on minimal containers where LANG is unset, grep does no non-ASCII folding at all, so an accented capital will not match its lowercase form. A UTF-8 locale enables Unicode-aware folding. Force it for one command:
LC_ALL=en_US.UTF-8 grep -i 'pattern' file.txtThe canonical trap is the Turkish dotted-i: under tr_TR.UTF-8, I and i do not fold to each other the way they do in English locales, so a script searching for INDEX can silently miss index on a Turkish-locale host. Force LC_ALL=C or LC_ALL=en_US.UTF-8 for ASCII identifier searches that must be deterministic. For pure ASCII text none of this matters.
Make only part of a pattern case-insensitive
-i is all-or-nothing. PCRE mode (grep -P, GNU only) supports the inline (?i) flag, which turns case-insensitivity on from that point in the pattern onward, and (?i:...), which scopes it to one group:
grep -P '(?i):pattern' app.logPowerShell's .NET regex understands (?i) and (?i:...) the same way, which is why the Windows variant pairs -CaseSensitive with an inline (?i) to flip just the relevant span.
When not to use -i
Drop -i when case is meaningful data: MAX_RETRIES (a constant) versus maxRetries (a variable), User the class versus user the instance, PATH the variable versus path in a comment. Use -i for human-written prose (logs, messages, docs) and leave it off for code identifiers, where capitalization is a deliberate signal. Also avoid stacking -i on a pattern like [Ee]rror that already spans both cases: it makes every other letter case-insensitive too.
Match a whole word with grep
grep cat file also hits category, concatenate, scatter and wildcat, because grep matches substrings by default. grep -w 'cat' file matches only when the pattern stands alone with a word boundary on each side.
grep -w ':pattern' :search_pathPowerShell has no -w, so the Windows variant uses explicit \b anchors in the .NET regex.
What counts as a word boundary
A word character is a letter, a digit, or the underscore. Everything else (spaces, punctuation, slashes, dots, line start and end) is a non-word character, and -w requires a non-word character or line edge immediately before and after the match. The underscore is the part people forget: grep -w 'user' will not match user_id or _user, which silently drops every compound identifier in a snake_case codebase. The test only looks at the characters just outside the match, so punctuation inside the pattern is fine: grep -w '1.2.3' matches v 1.2.3 but not 1.2.34 or v1.2.3, and grep -w "don't" matches a line containing don't. The flip side is that the apostrophe is itself a boundary, so grep -w 'don' also matches don't. Add -F when the pattern holds dots or other regex metacharacters you mean literally.
Word boundaries by hand: \b and < >
When you need a boundary on only one side, or inside a larger pattern, write it yourself. The classic BRE anchors \< (start of word) and \> (end of word) work on both GNU and BSD grep:
grep '\<:pattern\>' :search_pathGNU grep and current macOS grep both accept the Perl-style \b (grep -E '\bword\b') as a word-boundary assertion, but POSIX does not define it, so other grep implementations are free to treat it differently, and \< and \>, or plain -w, are the safer choice in scripts that travel.
-w with alternation, and -x for a whole line
-w applies to the whole match, not to each word inside the pattern. grep -w 'hot dog' matches a hot dog please but not hot dogs. With an alternation, add -E so the bar is parsed; then each branch must sit on boundaries:
grep -wE '(cat|dog|fish)' pets.txtWithout -E, grep -w 'cat|dog' looks for the literal string cat|dog and usually matches nothing.
-x is the stricter cousin: the pattern must equal the entire line.
| Flag | Matches | cat matches the line... |
|---|---|---|
| (none) | substring anywhere | concatenate, the cat sat |
-w | whole word, boundaries on both sides | the cat sat, not concatenate |
-x | the whole line, nothing else on it | cat, not the cat sat |
grep -Fxq 'value' allowlist.txt is the canonical "is this entry in the list" test in shell scripts: it exits 0 if value is a whole line in the file, treating the pattern as a fixed string.
Search multiple patterns
The fastest way to OR several patterns is extended-regex alternation: grep -E 'ERROR|WARN|FATAL' app.log prints every line that matches any of the three. grep gives you three mechanisms, each with a different tradeoff:
| Method | Form | Best for |
|---|---|---|
-e per pattern | grep -e 'A' -e 'B' | A handful of patterns kept separate from each other |
-E alternation | grep -E 'A|B' | One regex with branches |
-f from a file | grep -f patterns.txt | Long or machine-generated pattern lists |
grep -E ':pattern|WARN|FATAL' app.loggrep -e ':pattern' -e 'timeout' -e 'refused' app.log-e vs -E. -e PATTERN adds one pattern and does not change the regex flavor, so under -e alone the bar is a literal pipe. -E switches to extended regex, where the bar means alternation inside a single pattern. They combine: grep -E -e 'A|B' -e 'C|D' file is valid. -e is also the way to pass a pattern that starts with a dash. Note that -e isolates a pattern but does not make it literal: a dot is still "any character" unless you add -F.
-f reads patterns from a file, one per line, each treated like an -e. Pair it with -F for a large literal list, the classic case being an access log against a blocklist:
cut -d, -f1 blocked-ips.csv > patterns.txt
grep -F -f patterns.txt access.log
# or skip the temp file with process substitution
grep -F -f <(cut -d, -f1 blocked-ips.csv) access.logWatch for a trailing blank line in the pattern file: an empty pattern matches every line, so the "filtered" output becomes the whole file. Strip blanks with grep -v '^$' raw.txt > patterns.txt.
On PowerShell, Select-String -SimpleMatch -Pattern 'a','b' is the -F -e equivalent and -Pattern (Get-Content patterns.txt) is the -f equivalent.
AND: lines that contain all patterns
Every method above is OR. grep has no single-pass AND flag. Chain greps instead, each filtering the previous survivors (put the most selective pattern first):
grep ':pattern' app.log | grep 'user=42'On GNU grep, PCRE lookahead expresses AND in one pattern, because each (?=.*X) asserts "X appears somewhere ahead" without consuming input:
grep -P '(?=.*ERROR)(?=.*user=42)' app.log-P does not exist on macOS BSD grep, so chaining is the portable answer. For "A and (B or C) but not D", a small awk script is clearer than a five-stage pipe.
Exclude matching lines (invert match)
grep -v 'pattern' file prints every line that does not match. The per-line match decision is unchanged; -v prints the other set. PowerShell's equivalent is -NotMatch.
grep -v ':pattern' app.logExclude several patterns with repeated -e (literal-friendly) or one -vE alternation:
grep -v -e 'DEBUG' -e 'TRACE' app.log
grep -vE 'DEBUG|TRACE|INFO' app.logThe most useful -v recipe strips comments and blank lines so you can read what a config file actually does:
grep -vE '^(#|$)' nginx.conf^(#|$) is "starts with #, or is empty". Anchor the #: a bare grep -v '#' also drops valid lines that merely contain a # in a value or URL. If comments are indented, ^\s*# is the more robust pattern.
-v composes with the rest: -vc counts non-matching lines (it sums with grep -c for the same pattern to the file's total line count), -iv excludes in any case, and -vw excludes only the standalone word, so grep -vw 'log' leaves login, catalog and dialog alone where grep -v 'log' drops them. grep -rnv works too, but across a whole repository "every line without DEBUG" is almost the entire codebase, so scope it.
The double-negative trap
grep -vE 'error|warn' keeps lines that contain neither word. Inverting an OR gives an AND of negations (De Morgan's law): NOT (error OR warn) = (NOT error) AND (NOT warn). A pipeline of grep -v stages is also an AND. If you genuinely need "lacks A or lacks B", grep cannot express it in one pass; use awk with an explicit boolean condition.
Three more -v traps:
-vlis not "files without a match".grep -vl 'pattern' *lists files with at least one non-matching line, which is nearly every file. You want-L.-voprints nothing useful. With-vthere is no matched portion to print.grep -v '.'drops every non-empty line, because.is any character. Usegrep -vF '.'for a literal dot.
The ps aux | grep ssh | grep -v grep idiom works but is fragile. grep '[s]sh' is the robust trick: the bracket expression matches ssh, but the literal text [s]sh in the grep process's own command line does not match itself.
Recursive search
Search a whole tree. Full reference: how to grep recursively.
grep -rn ':pattern' :search_path-r is recursive, -n prints line numbers. Add -I (capital i) to skip binary files, which both GNU and BSD support:
grep -rnI ':pattern' :search_pathWorth knowing: GNU -r follows a symlink only when you name it on the command line, and GNU -R follows every symlink it meets. On macOS -r and -R are the same flag and neither follows symlinks by default; add -S to follow all of them or -O to follow only the ones on the command line. If a script depends on symlink behavior, use -R on Linux and -R -S on macOS.
Filtering by filename
GNU grep has --include, --exclude and --exclude-dir. Current macOS grep supports --exclude-dir, but older BSD builds lack these flags, so the fully portable route is find piped into xargs.
grep -rn --include='*.ts' 'useState' src/Excluding directories (here node_modules and .git, case-insensitively):
grep -rin --exclude-dir=node_modules --exclude-dir=.git ':pattern' :search_pathIf you live on macOS and want the GNU flags everywhere, brew install grep gives you GNU grep as ggrep. See the find command cheat sheet for the find | xargs pattern in more depth.
Context lines
Show N lines after, before, or around each match. Critical for log triage.
| Flag | Meaning |
|---|---|
-A N | N lines After |
-B N | N lines Before |
-C N | N lines of Context (N before and N after) |
grep -C 3 'Exception' app.log-A, -B, -C all work on BSD and GNU. The long forms (--after-context, --before-context, --context) work on GNU and current macOS grep; stick to the short flags if a script may meet an older BSD build.
List only filenames
-l prints each file that contains a match once, with no line output. -L (capital) lists the files with no match.
grep -rl ':pattern' :search_pathCount matches with grep
grep -c 'pattern' file counts matching lines, not occurrences. A line that contains the pattern three times adds 1. That gap is the single most common surprise with grep counting.
grep -c ':pattern' app.logTake a file quote.txt with one line, the cat sat on the mat near the door:
grep -c 'the' quote.txt
# 1
grep -o 'the' quote.txt
# the
# the
# the
grep -o 'the' quote.txt | wc -l
# 3-o prints each match on its own line, and wc -l counts them. That is the occurrence count:
grep -o ':pattern' app.log | wc -lPowerShell has the same split: (Select-String ...).Count counts lines, -AllMatches plus .Matches.Count counts occurrences. Passing -c and -o together does not give occurrences; -c wins and you still get a line count. And -o counts non-overlapping matches: aa against aaaa reports two, not three.
Per-file counts and totals
grep -rc prints one file:count line per file searched, including a :0 for every file with no match. Filter the noise, or sum the counts with awk:
grep -rc 'TODO' . | grep -v ':0$' # only files with hits
grep -rc 'TODO' . | awk -F: '{s+=$2} END {print s}' # total matching lines
grep -ro 'TODO' . | wc -l # total occurrences across the tree./src/api.ts:4
./src/utils.ts:0
./src/index.ts:1
./README.md:0
Symlink handling differs too (GNU -R follows every symlink, macOS -R follows none unless you add -S), so a tree with symlinked directories can produce different totals on macOS and Linux. Use -R on Linux and -R -S on macOS if the numbers must match.
Two more counting gotchas: grep -c prints 0 and exits with status 1 when nothing matches, which aborts a set -e script (append || true or test the value); and a file with \r\n line endings or no final newline can make grep -c and wc -l disagree by one (inspect with file or cat -A).
Count unique matches
grep -o 'pattern' file | sort | uniq -c | sort -rn answers "how many of each": it pulls every match out, groups identical ones, prefixes each group with its count, and ranks the most frequent first.
grep -oE ':pattern' :search_path | sort | uniq -c | sort -rn | head -10Each stage does one job. grep -o reduces every line to the token you want to tally (skip it and you count whole log lines, nearly all distinct, so every count is 1). sort makes identical matches contiguous. uniq -c collapses each run and prefixes its length. sort -rn ranks numerically, highest first, and head caps the leaderboard.
Why sort must come before uniq
uniq only compares each line with the one immediately before it. Given GET, POST, GET, GET, POST, uniq -c reports:
1 GET
1 POST
2 GET
1 POST
That is a count of unbroken runs, not of unique values. Sort first and you get 3 GET and 2 POST. If you ever see the same key twice in uniq -c output, you skipped the sort.
Worked examples
# Top client IPs in an access log (^ keeps an IP inside a URL from counting)
grep -oE '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' access.log | sort | uniq -c | sort -rn | head -10
# Count each HTTP status code (field 9 in the combined log format)
awk '{print $9}' access.log | sort | uniq -c | sort -rn
# Most common error message
grep -oE 'ERROR.*' app.log | sort | uniq -c | sort -rn | head
# Distinct users, and how many there are
grep -oE 'user=[a-z0-9_]+' app.log | sort -u
grep -oE 'user=[a-z0-9_]+' app.log | sort -u | wc -lIf error messages carry variable parts (timestamps, request IDs), the counts fragment; strip those with sed first or count a stable prefix. sort -u is sort | uniq in one step when you want the distinct list and not the counts.
| Flag | What it keeps (input must be sorted) |
|---|---|
uniq -c | Every distinct line, prefixed with its count |
uniq -d | Only lines that appear more than once |
uniq -u | Only lines that appear exactly once |
uniq (no flag) | One copy of each distinct line, no count |
sort and uniq compare bytes, so GET and get are separate; normalize with tr A-Z a-z first, or use sort -f | uniq -i -c (careful: uniq -f skips fields, it is uniq -i that ignores case). These flags behave the same on BSD and GNU; the exception is sort -h, which is GNU and only landed in newer BSD sort.
Huge files: count in one awk pass
Past a few hundred megabytes the sort stage becomes the bottleneck, because it orders the entire stream before uniq sees a line. An awk associative array counts in a single pass and only sorts the small final table:
awk '{c[$0]++} END {for (k in c) print c[k], k}' big.log | sort -rn | headThe tradeoff: awk holds one hash entry per distinct value, so it struggles when there are millions of unique keys.
grep and print a column
grep 'pattern' file | awk '{print $2}' keeps the matching lines and prints the second whitespace-separated field of each. grep is a line filter that knows nothing about columns; awk understands columns natively.
grep ':pattern' access.log | awk '{print $2}'PowerShell has no awk, so ForEach-Object splits each matched line on whitespace and indexes into it; arrays are zero-based, so the second column is index 1.
awk field basics. $1 is the first field, $0 the whole line, $NF the last field (NF holds the number of fields), and $(NF-1) the second-to-last. By default awk splits on runs of spaces and tabs and trims leading and trailing whitespace, so padded output still gives the first visible word as $1.
# Custom separator: username and shell from the colon-delimited passwd file
awk -F: '{print $1, $7}' /etc/passwd
# Several columns; the comma inserts the output separator, OFS changes it
grep ':pattern' access.log | awk '{print $1, $3}'
awk -v OFS=',' '{print $1, $3}' access.log
# Unique IPs that hit a status code (client IP is field 1 in the combined format)
grep ' 404 ' access.log | awk '{print $1}' | sort -u
# PIDs of matching processes (pgrep does this in one step)
ps aux | grep 'nginx' | grep -v grep | awk '{print $2}'For CSV use -F',', for tabs -F'\t'; the separator can be a regex, so -F'[,;]' splits on either character. Drop the comma in print $1 $3 and the fields are glued together with no gap.
awk can do the filtering itself. awk '/pattern/ {print $2}' file is exactly equivalent to the pipe, with one fewer process. Keep grep in the pipe only when you need a regex feature awk lacks, such as a GNU grep -P lookbehind.
grep -o covers shape, awk covers position. If the value is identifiable by shape (an IP, a UUID, an email), grep -oE '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' access.log extracts it wherever it sits. If it is "the third field", you need awk or cut.
cut for single-character delimiters. grep 'sshd' /etc/passwd | cut -d: -f1 is lighter than awk, and -f1,3 or -f2- select several fields. But cut does not collapse repeated delimiters, so on whitespace-aligned output like ps or ls -l a run of spaces produces empty fields. Use awk for anything whitespace-aligned.
Three mistakes account for most "awk printed nothing" reports: forgetting -F on a non-whitespace file (so $1 equals the whole line), writing "$2" (a literal string) instead of $2, and double-quoting the program so the shell expands $2 before awk sees it. Always single-quote the awk program. macOS ships BSD awk and most Linux distributions ship gawk; for field extraction they behave the same, and only gawk-specific features like gensub() need brew install gawk. For JSON use jq, and for CSV with quoted commas use a CSV-aware tool such as csvcut, xsv or mlr, not awk -F','.
grep regex: BRE vs ERE vs PCRE
grep has three regex engines, and the flag picks one. The same pattern can match different text, or fail, depending on the mode.
| Mode | Flag | What it gives you | Available on |
|---|---|---|---|
| Basic (BRE) | none (default) | Bare . * ^ $ [...]; plus, question mark, bar, parens and braces need backslashes | GNU, BSD |
| Extended (ERE) | -E | Plus, question mark, bar, parens and braces work bare | GNU, BSD |
| Perl-compatible (PCRE) | -P | Lookahead, lookbehind, non-greedy *?, \d, named groups | GNU only |
ERE is what most people mean by "regex" today. Reach for -E by default. egrep and fgrep are deprecated shorthands for grep -E and grep -F.
BRE: the default, where metacharacters are literal
In basic regex, + ? | ( ) { } match themselves. To use them as metacharacters you escape them, which is the inversion that makes people give up on plain grep. The same three tasks in each mode:
BRE: grep '[0-9]\+' app.log
ERE: grep -E '[0-9]+' app.log
BRE: grep '\(error\|warn\)' app.log
ERE: grep -E '(error|warn)' app.log
BRE: grep 'a\{2,4\}' app.log
ERE: grep -E 'a{2,4}' app.log
So plain grep '[0-9]+' looks for a digit followed by a literal plus sign, and in ERE an escaped \( matches a literal paren while a bare ( starts a group. Pick a mode and commit to its rules. BRE stays the default because it is the original grep behavior frozen by POSIX.
grep -E '(error|warn|fatal)' app.logPCRE: lookaround, \d and non-greedy
grep -P adds lookahead (?=...) and (?!...), lookbehind (?<=...) and (?<!...), non-greedy quantifiers, the \d \w \s shorthands and their negations, named groups and backreferences. Lookbehind is the headline feature: it pulls the value after user= without including user= in the match.
grep -oP '(?<=user=)\w+' app.logNon-greedy matching is the other thing ERE cannot do: grep -oP '".*?"' data.json stops at the first closing quote. -P is a compile-time option in GNU grep, so some minimal Linux builds reply grep: support for the -P option has not been compiled in. PowerShell's .NET engine supports lookaround and \d natively.
One task, three flavors (one or more digits followed by ms):
BRE: grep '[0-9]\+ms' app.log
ERE: grep -E '[0-9]+ms' app.log
PCRE: grep -P '\d+ms' app.log
\d is not in BRE or ERE
\d looks universal because it works in Python, JavaScript and PCRE, but POSIX BRE and ERE do not define it. On GNU grep in BRE/ERE mode it is not a digit class, so grep -E '\d{3}' does not find three digits on Linux. Current macOS grep does accept \d as a digit shortcut, which is exactly how a pattern that works on a Mac breaks on a server. Use a POSIX class or a range for anything portable:
| Perl shorthand | POSIX class (BRE/ERE) | Explicit range |
|---|---|---|
\d | [[:digit:]] | [0-9] |
\w | [[:alnum:]_] | [A-Za-z0-9_] |
\s | [[:space:]] | (no clean range) |
\D | [^[:digit:]] | [^0-9] |
POSIX classes are locale-aware: in a non-ASCII locale [[:alpha:]] matches accented letters that [A-Za-z] misses. GNU grep and current macOS grep both accept \w and \b as extensions in BRE and ERE, but POSIX does not require them, so the POSIX classes are the portable form.
Two smaller differences: POSIX ERE does not specify the backreference \1 that BRE has (GNU and current macOS grep both accept it in -E mode as an extension, so echo abab | grep -E '(ab)\1' matches on both), and an unterminated interval like grep -E 'a{2,' is accepted as literal text on some builds and an error on others, so always close the brace. For a fixed string such as 192.168.1.1 or Cmd+Shift+P, skip regex entirely and use -F. For the full syntax, see the regex cheat sheet. For specific patterns: match an email address, match a URL, match a hex color code.
macOS BSD vs GNU grep
The differences that matter, in order of how often they bite.
| Feature | GNU grep | BSD grep (macOS default) |
|---|---|---|
-P (PCRE, (?i), lookaround) | Supported (if compiled in) | Not supported |
--exclude-dir=DIR | Supported | Supported by current macOS grep; missing on older BSD builds |
--include / --exclude | Supported | Missing on older BSD builds; check man grep |
--color=auto | Supported | Supported (never, always, auto) |
--context long form | Supported | Supported on current macOS |
| Recursive symlinks | -r: command-line links only; -R: all | Not followed by default; -S all, -O command-line only |
\b word boundary | Supported | Supported on current macOS |
\w word character class | Supported | Supported on current macOS ([[:alnum:]_] is the portable form) |
\d in BRE/ERE | Not a digit class | Digit shortcut on current macOS (use [[:digit:]] to be portable) |
Backreference \1 in ERE | Yes (extension) | Yes on current macOS (extension) |
-i, -w, -x, -v, -c, -o, -e, -f, -F, -E | Supported | Supported, identical |
The same GNU-versus-BSD split bites find even harder than it bites grep, so if you write portable shell across macOS and Linux it is worth knowing where BSD find and GNU find diverge before a script silently does the wrong thing on one platform.
Quick fix on macOS: install GNU grep via Homebrew and use it as ggrep, or alias it. Alternatives for PCRE are pcregrep (brew install pcre, which also matches across lines with -M) and ripgrep with rg --pcre2.
brew install grep
alias grep='ggrep'
alias egrep='gegrep'
alias fgrep='gfgrep'Add to ~/.zshrc (or ~/.bash_profile) and reload. Scripts you ship to teammates should not assume GNU grep is present; either invoke ggrep explicitly, or stick to the BSD-compatible subset.
grep vs ripgrep vs ag
grep, ripgrep (rg) and ag (the_silver_searcher) answer the same question, which lines in these files match a pattern, and differ in two things that matter day to day: speed, and what they search by default. My rule: rg for interactive code search inside a repo, grep for anything that has to run anywhere, and ag only if it is already in your fingers.
- grep ships on every Unix-like system, follows POSIX, and searches exactly what you point it at. Recursion is opt-in with
-r. - ripgrep is a Rust tool by Andrew Gallant built to search source trees fast. It recurses by default, prints line numbers and color, and skips anything in
.gitignore, hidden files and binaries. - ag was written in C as a faster,
.gitignore-aware alternative toackand was the fast-grep everyone reached for beforeripgrep. It still works and still ships in package repositories, butripgrepis faster and more actively maintained. The lineage isack(Perl, 2005) thenagthenripgrep, each faster than the last.
| Property | grep | ripgrep (rg) | ag |
|---|---|---|---|
| Typical speed on a large repo | Slowest | Fastest | Fast |
| On every system by default | Yes | No (install) | No (install) |
Respects .gitignore | No | Yes (default) | Yes (default) |
| Skips hidden and binary files | No | Yes (default) | Yes (default) |
| Recursive by default | No (needs -r) | Yes | Yes |
| Parallel across CPU cores | No | Yes | No |
| Regex engine | BRE / ERE, PCRE via -P (GNU only) | Rust regex; PCRE2 via --pcre2 | PCRE |
| Multiline search | No (line-oriented) | Yes (-U / --multiline) | Limited |
| Replace preview | No | Yes (-r replacement text with capture groups) | No |
| Line numbers and color by default | No | Yes | Yes |
Why ripgrep is fast, and what it skips
ripgrep searches several files concurrently across all CPU cores, memory-maps files where that helps, and uses Rust's finite-automata regex crate (no catastrophic backtracking) with SIMD-accelerated literal scanning. The part people underestimate is that it searches less: a grep -r in a Node project walks every byte of node_modules, while rg skips the whole directory because git already ignores it.
That default is also the surprise. rg pattern skips files matched by any .gitignore, .ignore or .rgignore in scope, hidden files and directories, and binary files. Add --hidden for dotfiles (a value in .env or .github/workflows/), --no-ignore to search ignored paths (dist/bundle.js), or -uuu to disable all filtering so rg behaves like grep -r. The same recursive search, both ways:
grep -rn ':pattern' :search_path
rg ':pattern' :search_path
rg -uuu ':pattern' :search_pathGoing the other way, grep has no idea .gitignore exists, so you spell the junk directories out yourself with grep -rn --exclude-dir=node_modules --exclude-dir=.git. That verbosity is exactly what ripgrep exists to remove.
Regex engines differ between the three
Plain rg supports \d, \w, \b, named groups and Unicode classes, but deliberately not backreferences or lookaround, because its finite-automata design guarantees linear-time matching. Pass --pcre2 when you need them. ag uses PCRE throughout, so lookaround works unflagged. A lookahead pattern therefore works in grep -P, rg --pcre2 and ag, but not in plain rg.
Install ripgrep, and when not to rely on it
sudo apt install ripgrepThe binary is rg on every platform. On older Debian or Ubuntu releases without the package, use the release binary from the project's GitHub page or cargo install ripgrep. ag installs as the_silver_searcher (apt install silversearcher-ag, brew install the_silver_searcher).
Two traps when switching. First, rg -r is not recursive: recursion is already the default, and -r is the replacement flag. Second, a CI script that calls rg works on your laptop and fails on a fresh build agent or slim container with rg: command not found. For deploy hooks, CI steps, minimal images and locked-down servers, use grep, or have the script install ripgrep and check it exists first.
Common pitfalls
1. Unquoted patterns get shell-expanded. With grep *.log file, the *.log is expanded by the shell into a list of files before grep ever runs. Always quote: grep '*.log' file.
2. Patterns starting with - are read as flags. grep -test file fails because grep tries to parse -t as a flag. Use grep -- -test file or grep -e '-test' file.
3. Forgetting -E, so | is literal. grep 'ERROR|WARN' app.log searches for the literal string ERROR|WARN and finds nothing. Add -E or use two -e flags.
4. grep -E does not enable PCRE. ERE adds +, ?, alternation, groups and intervals, but not lookaheads or non-greedy *?. Those are PCRE only (GNU -P or PowerShell). \d is not POSIX ERE either; current macOS grep happens to accept it, GNU grep does not.
5. Expecting -c to count occurrences. It counts lines. Use grep -o 'pattern' file | wc -l.
6. Confusing -i with -I. Lowercase ignores case; uppercase skips binary files. grep -riI does both.
7. A pattern that works on a Mac fails on Linux. Current macOS grep quietly accepts \d in -E mode; GNU grep does not treat it as a digit. Write [[:digit:]] (or [0-9]) and the same command works on both.
8. grep -r symlink semantics differ. GNU -r follows only symlinks named on the command line and -R follows all; macOS follows none unless you pass -S (or -O for command-line ones). If your search misses (or duplicates) files depending on the host, this is why.
9. grep exits 1 when there is no match. Useful in scripts, surprising in pipelines: set -e will abort the script if no line matches. Either disable set -e for that line or wrap with || true.
10. Multi-line patterns do not work. grep is line-oriented and no regex mode changes that. To match across newlines, use pcregrep -M, ripgrep --multiline, or pipe through tr '\n' ' ' first.
11. PowerShell's Select-String returns objects, not strings. Use .Line or .Matches.Value when consuming output programmatically. findstr in cmd.exe returns text but has weaker regex; prefer Select-String for anything beyond a literal search.
12. Grepping structured data. For JSON use jq, for YAML yq, for CSV a CSV-aware parser. Line-oriented matching will happily hit inside a string value or split a quoted field.
What to do next
Deep dives for the tasks that still have their own page:
- How to grep recursively through a directory: the
-r/-Rreference,-land-L, and--include,--exclude,--exclude-dir - How to show lines before and after a match:
-A,-B,-C
Related cheat sheets:
- find command cheat sheet: the natural pair for
grepwhen you need to filter by filename first. - SSH cheat sheet: for greping logs on remote hosts over SSH.
- curl cheat sheet: when the pipeline starts with an HTTP response you want to grep.
- regex cheat sheet: full regex reference for crafting the patterns you feed into
grep -E/-P. - Bash for loop and Bash while loop: looping over filenames with
grep -loutput. - External: GNU grep manual, FreeBSD grep(1), PowerShell Select-String, GNU awk manual, GNU coreutils: sort, GNU coreutils: uniq.
FAQ
macOS ships BSD grep, which has no PCRE engine, so the -P flag fails with an invalid option error. You have three options: install GNU grep via Homebrew (brew install grep) and use it as ggrep, install pcregrep as a standalone PCRE tool, or use ripgrep with --pcre2.
If the pattern does not genuinely need lookbehind, \d, or non-greedy quantifiers, rewrite it in ERE (-E) with POSIX classes like [[:digit:]] and it will run on both platforms.
egrep is shorthand for grep -E (extended regex). fgrep is shorthand for grep -F (fixed strings, no regex). Both are now deprecated wrappers; modern systems print a warning and recommend the grep -E / grep -F form. Write the long form in any script you commit.
Use grep -F when the pattern is a literal string with regex metacharacters in it (IP addresses, file paths, URLs). It is faster and avoids the escaping trap.
-E selects extended regex (ERE), the POSIX standard: plus, question mark, bar, parentheses and braces work as metacharacters without backslashes, but there is no lookaround and POSIX defines no \d (current macOS grep accepts it, GNU grep does not). -P selects Perl-compatible regex, which adds lookahead, lookbehind, non-greedy quantifiers, named groups and the shorthand classes. -P is GNU-only.
It counts matching lines. If one line contains the pattern three times, grep -c adds 1. For the true number of occurrences, use grep -o 'pattern' file | wc -l; -o prints each match on its own line and wc -l counts them.
For the number of distinct values: grep -oE 'pattern' file | sort -u | wc -l. For a frequency breakdown: grep -oE 'pattern' file | sort | uniq -c | sort -rn. The sort before uniq is mandatory, because uniq only collapses adjacent duplicates.
grep has no single-pass AND. Chain greps so each filters the previous output: grep 'A' file | grep 'B'. On GNU grep you can also stack PCRE lookaheads in one pattern, which is single-pass but GNU only. On macOS BSD grep, chaining is the portable answer.
-w matches the pattern as a whole word anywhere on a line; other text can be present. -x matches only when the pattern equals the entire line. For the line the cat sat, grep -w 'cat' matches but grep -x 'cat' does not. Use grep -Fxq for exact membership checks in scripts.
grep -L 'pattern' files lists files with no matching line at all. grep -vl 'pattern' files lists files that have at least one line not matching the pattern, which is nearly every file. If you want "files that do not contain the pattern", use -L.
-i reliably folds case only for ASCII letters A to Z. Non-ASCII case folding depends on your locale. Under the C or POSIX locale, common on minimal containers, grep does no non-ASCII folding at all. Run locale to check, and force a UTF-8 locale for one command with LC_ALL=en_US.UTF-8 grep -i 'pattern' file.
On GNU grep, and on current macOS grep: grep -rn --exclude-dir=node_modules --exclude-dir=.git 'pattern' .. You can pass --exclude-dir multiple times.
On older BSD grep builds without --exclude-dir, pipe find into xargs with -prune: find . -type d \( -name node_modules -o -name .git \) -prune -o -type f -print0 | xargs -0 grep -n 'pattern'.
The portable way is ANSI-C quoting in Bash: grep $'\\t' file.txt. The $'...' form interprets \t as a literal tab before passing the argument to grep.
With -P on GNU grep, grep -P '\t' file.txt works because PCRE interprets \t. With -E alone, \t is treated as a literal backslash-t, which is almost never what you want.
grep is line-oriented; it reads one line at a time and applies the pattern to each. A regex with \n in it will never match because the newline is the record separator, not part of the input.
Workarounds: use pcregrep -M (multi-line PCRE), ripgrep --multiline, or preprocess the input to a single line with tr '\\n' ' ' before grepping. For structured data like JSON, prefer jq over multi-line grep.
PowerShell's Select-String cmdlet is the modern equivalent and supports .NET regex (which covers most of what GNU PCRE does). Unlike grep it is case-insensitive by default; add -CaseSensitive when case matters. For recursion, pipe Get-ChildItem -Recurse -File into it. The cmd.exe findstr command works for literal strings and basic patterns but has weaker regex.
On Windows 10 and later, the WSL Linux subsystem ships GNU grep, so wsl grep ... works exactly like Linux. Git for Windows also ships a Bash environment with GNU grep available.
Because ripgrep skips files matched by .gitignore, hidden files (anything starting with a dot), and binary files by default, while grep searches whatever path you give it. Add --no-ignore for ignored paths, --hidden for dotfiles, or rg -uuu to disable all filtering and behave like grep -r.
For new setups, ripgrep. It is faster than ag (the_silver_searcher), more actively maintained, and adds multiline matching, search-and-replace preview and a PCRE2 mode. If ag is already in your muscle memory and works, there is no urgent reason to switch, but nothing it does is better.
Mostly. rg (ripgrep) is faster on large repositories, respects .gitignore by default, and has saner defaults (recursive, color, line numbers). The flags are similar but not identical: rg uses its own ERE-like engine by default with PCRE2 available via --pcre2.
For one-off log searches on production servers where you cannot install extras, stay with grep. For local development inside a repo, rg is usually the better choice.
Sources
Authoritative references this article was fact-checked against.
- GNU project documentationgnu.org
- grep(1), GNU grep manual page (Debian)manpages.debian.org
- grep(1), macOS 26.7 manual pageman.freebsd.org
- re_format(7), macOS 26.7 regular expressionsman.freebsd.org
- uniq(1), GNU coreutils manual page (Debian)manpages.debian.org
- ripgrep on GitHubgithub.com
- the_silver_searcher (ag) on GitHubgithub.com





