Tools › Cheat sheets › Linux & Shell › grep
🔎

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

CommandWhat it does
grep "text" fileLines containing text.
grep -i "text" fileIgnore case.
grep -n "text" fileShow line numbers.
grep -v "text" fileInvert: lines that do NOT match.
grep -c "text" fileCount matching lines.
grep -w "word" fileMatch whole words only.
grep -x "exact line" fileMatch whole lines only.
grep -o "pattern" filePrint only the matching part.

Search many files

CommandWhat 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

CommandWhat it does
grep -A 3 "text" fileShow 3 lines after each match.
grep -B 3 "text" fileShow 3 lines before.
grep -C 3 "text" fileShow 3 lines around.
grep -E "error|warn" fileMatch either word.
grep -e "one" -e "two" fileMultiple patterns.
grep -F "a.b*c" fileTreat the pattern as plain text (no regex).
grep -P '\d{3}-\d{4}' filePerl regex, such as digit shortcuts.
grep -E '^[0-9]+$' fileLines that are only digits.

In pipelines

CommandWhat it does
ps aux | grep nginxFind 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 errorSearch kernel messages.
grep -q 'text' file && echo foundQuiet mode: only set the exit status.
grep -h 'text' *.logHide 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.

More Linux & Shell cheat sheets

🐚 Bash🔍 find✂️ sed🧮 awk📦 tar📝 Vim🪟 tmux🔐 chmod permissionsAll Linux & Shell cheat sheets →
Copied to clipboard