Skip to content

grep

Terminal window
grep [options] "pattern" file
command | grep [options] "pattern"

FlagPurposeExample
-iCase-insensitivegrep -i "error" log.txt
-r / -RRecursive (search directories)grep -r "TODO" src/
-nShow line numbersgrep -n "main" app.py
-cCount matching linesgrep -c "404" access.log
-lList filenames with matches onlygrep -rl "password" /etc/
-LList filenames without matchesgrep -rL "license" src/
-vInvert match (show non-matching lines)grep -v "^#" config.conf
-wMatch whole words onlygrep -w "port" config.txt
-oPrint only matched partgrep -oP '\d+\.\d+\.\d+\.\d+' log.txt
-A NShow N lines after matchgrep -A 3 "error" log.txt
-B NShow N lines before matchgrep -B 2 "error" log.txt
-C NShow N lines around matchgrep -C 5 "panic" syslog
-EExtended regex (same as egrep)`grep -E “(error
-PPerl-compatible regexgrep -P "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" file
-qQuiet mode (exit code only)grep -q "root" /etc/passwd && echo "found"
--includeFilter file types in recursive searchgrep -r --include="*.py" "import" .
--exclude-dirSkip directoriesgrep -r --exclude-dir=node_modules "TODO" .
--colorHighlight matchesgrep --color=auto "error" log.txt

Filter comments and blank lines from config

Section titled “Filter comments and blank lines from config”
Terminal window
grep -v "^#" /etc/ssh/sshd_config | grep -v "^$"
Terminal window
grep -oP '\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b' access.log
Terminal window
grep -rn --include="*.js" "addEventListener" src/
Terminal window
grep -rc "error" /var/log/ | grep -v ":0$"
Terminal window
ps aux | grep nginx
cat /etc/passwd | grep -c "/bin/bash"
dmesg | grep -i "usb"
history | grep "ssh"

CommandEquivalentRegex type
grepBasic regex (BRE)
egrepgrep -EExtended regex (ERE) — +, ?, `
fgrepgrep -FFixed strings (no regex, fastest)

egrep and fgrep are deprecated aliases but still work everywhere.


PatternMatches
^Start of line
$End of line
.Any single character
*Zero or more of preceding
+ (ERE)One or more of preceding
[a-z]Character range
[^0-9]Not a digit
\bWord boundary (with -P)
\dDigit (with -P)

  • ripgrep (rg) — faster recursive search, respects .gitignore, better defaults. Drop-in replacement for most grep -r use cases.