Skip to content

grep Command in Linux — 10 Practical Examples

The grep command is one of the most powerful tools in Linux. It searches text for patterns and is essential for developers, sysadmins, and anyone working with the command line.

Basic Syntax

grep [options] pattern [file...]

10 Practical Examples

1. Search a file for a word

grep "error" server.log

Prints every line in server.log containing “error”.

2. Case-insensitive search

grep -i "warning" server.log

Matches “warning”, “Warning”, “WARNING”, etc.

3. Count matches

grep -c "404" access.log

Prints only the number of matching lines, not the lines themselves.

4. Show line numbers

grep -n "TODO" main.py

Output: 42: # TODO: add error handling — the line number is shown before each match.

5. Search recursively in all files

grep -r "function" src/

Searches every file under the src/ directory.

6. Invert match (show lines that do NOT contain pattern)

grep -v "INFO" server.log

Useful for filtering out noise — show only warnings and errors.

7. Show context lines around matches

grep -B 2 -A 3 "Exception" app.log
  • -B 2 → 2 lines before the match
  • -A 3 → 3 lines after the match

8. Search whole words only

grep -w "cat" words.txt

Matches “cat” but not “catalog” or “catch”.

9. Use regular expressions

grep "^ERROR.*timeout" server.log

Lines starting with “ERROR” and containing “timeout” anywhere after.

10. Search for multiple patterns

grep -e "error" -e "warning" -e "critical" server.log

Matches any line containing any of the three patterns.

Common Options Quick Reference

OptionMeaning
-iCase-insensitive
-rRecursive
-nShow line numbers
-cCount matches
-vInvert match
-wWhole word match
-lList filenames only
-B nn lines before match
-A nn lines after match
-C nn lines around match

Pro Tip: Search with rg (ripgrep)

If you find yourself using grep heavily, try ripgrep (rg). It’s faster, respects .gitignore, and has better defaults:

rg "TODO" --type py

Install it with apt install ripgrep or brew install ripgrep.