grep

Search text for patterns and print matching lines.

What it does

grep scans text (files or streams) for matching patterns and outputs the lines that match. It is one of the core tools in Linux pipelines for filtering data.

How it works (mechanical)

Quick Start

# Basic search
grep "error" file.txt

# Case insensitive
grep -i "error" file.txt

# From pipe
dmesg | grep usb

Core Options (Most Useful Flags)

-i   Case-insensitive search
-v   Invert match (exclude)
-n   Show line numbers
-c   Count matches
-r   Recursive search
-w   Match whole words only
-x   Match entire line
-E   Extended regex (OR, +, ?)
-F   Fixed string (no regex, faster)
-o   Show only matching text
-l   Show filenames only (with matches)
-L   Show filenames with NO matches
-H   Always show filename
-h   Hide filename

Context & Output Control

-A 3   Show 3 lines AFTER match
-B 3   Show 3 lines BEFORE match
-C 3   Show 3 lines BEFORE and AFTER
--color=auto   Highlight matches

10 Practical Examples

# 1) Case-insensitive search
grep -i "error" app.log
# 2) Exclude lines
grep -v "debug" app.log
# 3) Show line numbers
grep -n "fail" app.log
# 4) Count matches
grep -c "error" app.log
# 5) Recursive search
grep -r "TODO" ./project/
# 6) Extended regex (OR)
grep -E "error|fail|warn" app.log
# 7) Fixed string (fast search)
grep -F "localhost" config.txt
# 8) Show context
grep -C 2 "panic" syslog
# 9) Only matching values
grep -o "[0-9]\+" file.txt
# 10) Find processes (classic pattern)
ps aux | grep nginx

Notes & Gotchas

Historical Context

The name grep comes from the ed editor command: g/re/p (global search, regular expression, print). It has been a core Unix utility since the 1970s.

Modern Equivalent

ripgrep (rg) and ag are faster and more feature-rich, but grep remains universal and foundational.

Related Commands