🔎
grep cheat sheet
grep prints lines that match a pattern. By default patterns are basic regular expressions; use -E for extended ones, -F for plain text and -P for Perl-style regex.
Click any command to copy it.
Basics
| Command | What it does |
|---|---|
grep "text" file | Lines containing text. |
grep -i "text" file | Ignore case. |
grep -n "text" file | Show line numbers. |
grep -v "text" file | Invert: lines that do NOT match. |
grep -c "text" file | Count matching lines. |
grep -w "word" file | Match whole words only. |
grep -x "exact line" file | Match whole lines only. |
grep -o "pattern" file | Print only the matching part. |
Search many files
| Command | What it does |
|---|---|
grep -r "text" dir/ | Search a directory recursively. |
grep -rn "text" . | Recursive with file name and line number. |
grep -rl "text" . | List only the names of matching files. |
grep -r --include="*.py" "text" . | Limit to certain file types. |
grep -r --exclude-dir=node_modules "text" . | Skip a directory. |
grep -rI "text" . | Ignore binary files. |
Context and patterns
| Command | What it does |
|---|---|
grep -A 3 "text" file | Show 3 lines after each match. |
grep -B 3 "text" file | Show 3 lines before. |
grep -C 3 "text" file | Show 3 lines around. |
grep -E "error|warn" file | Match either word. |
grep -e "one" -e "two" file | Multiple patterns. |
grep -F "a.b*c" file | Treat the pattern as plain text (no regex). |
grep -P '\d{3}-\d{4}' file | Perl regex, such as digit shortcuts. |
grep -E '^[0-9]+$' file | Lines that are only digits. |
In pipelines
| Command | What it does |
|---|---|
ps aux | grep nginx | Find a process (it will also match the grep itself). |
ps aux | grep '[n]ginx' | Trick to exclude the grep process from results. |
dmesg | grep -i error | Search kernel messages. |
grep -q 'text' file && echo found | Quiet mode: only set the exit status. |
grep -h 'text' *.log | Hide file names in the output. |
Frequently asked questions
What is the difference between grep, egrep and fgrep?
egrep is grep -E (extended regex) and fgrep is grep -F (fixed strings). The separate commands are deprecated in favour of the flags.
Is there a faster alternative?
ripgrep (rg) is much faster for large code bases and respects .gitignore by default.