grep – search for patterns in files

grep
grep

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

OptionDescription
-iCase-insensitive search
-vInvert match (show non-matching lines)
-rRecursive search in directories
-nShow line numbers
-lShow only filenames with matches
-cCount matching lines
-A NShow N lines after match
-B NShow N lines before match
-C NShow N lines before and after match
-EExtended regex (same as egrep)
-wMatch whole words only
-oShow only the matching part

Examples

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 -r with --include to search specific file types:

    grep -r --include="*.py" "import os" ~/projects/
    
  • Combine with find for complex searches:

    find . -name "*.log" -mtime -7 | xargs grep "error"
    
  • Use grep -q in scripts (quiet mode, just sets exit code):

    if grep -q "pattern" file.txt; then
      echo "Found!"
    fi
    
  • Consider ripgrep for faster searches in large codebases

See Also

  • 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

Tutorials