Basic Usage
Running grep
grep "pattern" file.txt # search in file grep "error" *.log # search multiple files grep "hello" file1.txt file2.txt # explicit file list cat file.txt | grep "pattern" # pipe input dmesg | grep -i "usb" # filter command output
Common Flags
-iCase-insensitive matching
-vInvert match — print non-matching lines
-cPrint count of matching lines
-nShow line numbers
-lList filenames with matches only
-LList filenames without matches
-wMatch whole words only
-xMatch whole lines only
Regex Patterns
Basic Regular Expressions (BRE)
.Any single character
*Zero or more of preceding element
^Start of line
$End of line
[abc]Character class — any of a, b, c
[^abc]Negated class — anything except a, b, c
[a-z]Range — lowercase letters
\<, \>Word boundaries (GNU)
\( \), \1Capture group and back-reference
BRE Examples
grep '^#' file.conf # lines starting with # grep 'error$' file.log # lines ending with error grep '^$' file.txt # blank lines grep 'col[ou]r' file.txt # match color or colour
Extended Regex
Extended Regular Expressions (ERE)
+One or more of preceding element
?Zero or one of preceding element
{n}Exactly n repetitions
{n,m}Between n and m repetitions
(a|b)Alternation — match a or b
( )Grouping (no backslash needed)
ERE Examples
grep -E '[0-9]{3}-[0-9]{4}' f # phone number pattern grep -E '(error|warn|fatal)' f # multiple patterns grep -E '^[A-Z][a-z]+' f # capitalized words grep -P '\d{1,3}\.\d{1,3}' f # Perl regex: IP fragments
Context Lines
Context Examples
grep -B 3 "error" app.log # 3 lines before match grep -A 5 "FAIL" test.log # 5 lines after match grep -C 2 "crash" kern.log # 2 lines before and after grep --group-separator="---" -C 1 "err" f # custom separator
Context Flags
-B NShow N lines before each match
-A NShow N lines after each match
-C NShow N lines before and after (context)
--group-separator=strSeparator between match groups (default --)
--color=autoHighlight matches in terminal
Recursive Search
Recursive Examples
grep -r "TODO" . # recursive from current dir grep -rn "FIXME" src/ # recursive with line numbers grep -r --include="*.py" "import" . # only .py files grep -r --exclude="*.log" "error" . # skip .log files grep -r --exclude-dir=node_modules "require" .
Recursive Flags
-r / --recursiveSearch directories recursively
-RLike -r but follows symlinks
--include=globSearch only files matching glob
--exclude=globSkip files matching glob
--exclude-dir=dirSkip directories matching name
--include-dir=dirOnly search directories matching name
Counting & Listing
Count & List Examples
grep -c "error" *.log # count matches per file grep -l "TODO" src/*.py # list files with TODOs grep -L "test" src/*.py # files missing "test" grep -o "http[^ ]*" page.html # extract matching parts only grep -c '' file.txt # count total lines (like wc -l)
Output Flags
-cPrint count of matching lines per file
-lPrint only names of files with matches
-LPrint only names of files without matches
-oPrint only the matched parts of lines
-H / -hShow / hide filename prefix
-ZNull-delimited output (for xargs -0)
Inverse Match
Invert & Exclude
grep -v "^#" config.conf # remove comment lines grep -v "^$" file.txt # remove blank lines grep -v -e "debug" -e "trace" app.log # exclude two patterns grep -v "pattern" f | grep "other" # chain: NOT A, then B
Filtering Strategies
-vInvert match — select non-matching lines
-v with -eExclude multiple patterns
pipe chainChain grep calls for complex filtering
grep -v '^$' | grep -v '^#'Remove blanks and comments
-v with -cCount non-matching lines
Multiple Patterns
Multiple Pattern Examples
grep -e "error" -e "warning" app.log grep -E "error|warning|fatal" app.log grep -f patterns.txt file.txt # patterns from file grep -w -e "GET" -e "POST" access.log
Pattern Options
-e patternSpecify a pattern (use multiple times)
-f fileRead patterns from file (one per line)
-E 'a|b|c'ERE alternation for multiple patterns
-FFixed strings — no regex, faster matching
-GBasic regex (default mode)
-PPerl-compatible regex (PCRE)
Performance
Performance Tips
-F (fgrep)Fixed-string mode — fastest for literal strings
LC_ALL=C grepBypass locale for 2-10x speedup on ASCII data
--include/--excludeReduce files searched before opening
-m NStop after N matches per file
-qQuiet mode — exit on first match (for scripts)
ripgrep (rg)Drop-in replacement; faster on large repos
Performance Examples
LC_ALL=C grep -F "exact string" huge.log grep -r -m 1 "needle" /var/log/ # stop after first hit grep -rq "pattern" . && echo "found" # boolean test grep -r --include="*.go" "func main" .
Common Patterns
One-Liners
grep -rn "TODO\|FIXME\|HACK" src/ # find code markers grep -oP '(?<=")[^"]+(?=")' f # extract quoted strings grep -E '^\s*$' f | wc -l # count blank lines grep -c '' *.py | sort -t: -k2 -rn # sort files by line count grep -rn --include="*.yaml" "password" . # audit for secrets
Recipes
IP addressesgrep -oE '[0-9]{1,3}(\.[0-9]{1,3}){3}'
Email addressesgrep -oE '[a-zA-Z0-9._%+-]+@[a-z.-]+'
URLsgrep -oE 'https?://[^ ]+'
Lines between markersgrep -A999 'START' f | grep -B999 'END'
Unique matchesgrep -oE 'pattern' f | sort -u
Count per patterngrep -c 'pat1' f; grep -c 'pat2' f