grep – search for patterns in files

grep searches for patterns in files and prints matching lines. It’s one of the most essential Unix tools — use it to find text in files, filter command output, or search through logs.
Synopsis
grep [OPTIONS] PATTERN [FILE...]
Quick Examples
# Find "error" in a log file
$ grep error /var/log/syslog
# Case-insensitive search
$ grep -i warning /var/log/messages
# Search recursively in a directory
$ grep -r "TODO" ~/projects/
# Show line numbers
$ grep -n root /etc/passwd
1:root:x:0:0:root:/root:/bin/bash
Common Options
| Option | Description |
|---|---|
-i | Case-insensitive search |
-v | Invert match (show non-matching lines) |
-r | Recursive search in directories |
-n | Show line numbers |
-l | Show only filenames with matches |
-c | Count matching lines |
-A N | Show N lines after match |
-B N | Show N lines before match |
-C N | Show N lines before and after match |
-E | Extended regex (same as egrep) |
-w | Match whole words only |
-o | Show only the matching part |
Examples
Basic Search
Find all lines containing “failed” in auth log:
$ grep failed /var/log/auth.log
Jan 30 08:15:22 server sshd[1234]: Failed password for invalid user admin
Jan 30 08:15:25 server sshd[1234]: Failed password for invalid user root
Search multiple files:
$ grep "function" *.js
app.js:function handleClick() {
utils.js:function debounce(fn, delay) {
Context Lines
Show 2 lines before and after each match:
$ grep -C 2 "ERROR" app.log
2026-01-30 09:14:58 INFO Starting process
2026-01-30 09:14:59 DEBUG Loading config
2026-01-30 09:15:00 ERROR Failed to connect to database
2026-01-30 09:15:00 DEBUG Retrying in 5s
2026-01-30 09:15:05 INFO Connection restored
Regular Expressions
Match lines starting with a date:
$ grep "^2026-" server.log
Match email addresses:
$ grep -E "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}" contacts.txt
Match IP addresses:
$ grep -E "\b[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\b" access.log
Filtering Output
Find processes (excluding the grep itself):
$ ps aux | grep nginx | grep -v grep
root 1234 0.0 0.1 nginx: master process
www-data 1235 0.0 0.2 nginx: worker process
Find files NOT containing a pattern:
$ grep -L "TODO" *.py
clean_module.py
finished_script.py
Tips
Use
-rwith--includeto search specific file types:grep -r --include="*.py" "import os" ~/projects/Combine with
findfor complex searches:find . -name "*.log" -mtime -7 | xargs grep "error"Use
grep -qin scripts (quiet mode, just sets exit code):if grep -q "pattern" file.txt; then echo "Found!" fiConsider ripgrep for faster searches in large codebases
See Also
Related Commands
- awk — Pattern scanning and processing
- sed — Stream editor for filtering and transforming text
- find — Search for files in directory hierarchy
- rg — ripgrep, faster grep alternative






