Skip to content

Grep Command Cheatsheet

Table of Contents

Command Structure

The grep command has two basic syntaxes:

Terminal window
grep [options] pattern [file...]
cat [file] | grep [options] pattern
  • pattern: Text or regular expression to search for
  • file: Target files (optional)
  • options: Modify search behavior

Basic Search Options

Terminal window
-i # Case insensitive
-w # Match whole words only
-x # Match entire lines only

Pattern Matching

Terminal window
-E # Extended regex (egrep)
-F # Fixed strings (fgrep)
-P # Perl regex syntax
-e # Multiple patterns

Context Control

Terminal window
-A n # Show n lines after match
-B n # Show n lines before match
-C n # Show n lines before and after

File Handling

Terminal window
-r # Recursive search
-R # Recursive (follow symlinks)
--include # Include only certain files
--exclude # Exclude certain files

Output Control

Terminal window
-o # Show only matched parts
-h # Suppress filename prefix
-H # Show filename prefix
--color # Colorize output

Performance Optimization

  1. Use Fixed Strings When Possible

    Terminal window
    grep -F "literal string" large_file.txt
  2. Limit Directory Search

    Terminal window
    grep --exclude-dir={.git,node_modules,dist} -r "pattern"
  3. Use Count for Large Files

    Terminal window
    grep -c "pattern" huge_file.txt

Real-World Examples

Terminal window
# Find errors and their context
grep -B2 -A1 "ERROR" /var/log/syslog
# Count errors by type
grep -o "ERROR:[^ ]*" logs.txt | sort | uniq -c
# Find IP addresses
grep -E "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b" access.log

Advanced Techniques

Pipeline Operations

Terminal window
# Search and replace
grep -l "old_text" *.txt | xargs sed -i 's/old_text/new_text/g'
# Complex filters
grep "error" log.txt | grep -v "debug" | sort | uniq -c
# Compressed files
zcat *.gz | grep "pattern"

Combining with Other Tools

Terminal window
# With find
find . -type f -exec grep "pattern" {} +
# With awk
grep "pattern" file.txt | awk '{print $2}'
# With xargs
grep -l "pattern" *.txt | xargs cp -t /backup/

Be careful with recursive searches in large directories. Use --exclude-dir for better performance.