Skip to content

    Grep Essentials

    Advanced grep patterns and commands.

    Quick recipes

    # HTTP 5xx lines in logs
    grep -E 'HTTP/(1|2) [5][0-9][0-9]' app.log
    
    # Find slow requests (> 2s)
    grep -E 'latency=(2000|[2-9][0-9]{3,})ms' app.log
    
    # JSON logs with PCRE2 (if available)
    grep -P '"level":\s*"error"(?:(?!\n\{).)*"requestId"' logs.json

    Production checklist

    • Prefer ripgrep (rg) for speed on large trees.
    • With grep -r, narrow scope using --include='*.ext' and --exclude-dir; skip vendor and node_modules.
    • NUL-safe pipelines: grep -Z with xargs -0.

    Get Uncommented Lines Only

    Drop comment and empty lines when reviewing active settings.

    grep -Ev '^(#|$)' /etc/ssh/sshd_config

    Alternative: grep -v '^#' file | grep -v '^$' achieves the same with two pipes

    Recursive Search with Context

    Recursive search with before/after context lines.

    grep -r -C 3 'pattern' /path/to/search/

    Options: -C 3 shows 3 lines before and after. Use -B 3 for before only, -A 3 for after only

    Count Pattern Occurrences

    Count lines (-c) or occurrences per line (-o with wc).

    # Count matching lines
    grep -c 'pattern' file.txt
    
    # Count total occurrences (including multiple per line)
    grep -o 'pattern' file.txt | wc -l

    Use case: Great for analyzing logs, counting errors, or tracking API calls

    Multiple Patterns (OR Logic)

    OR several patterns in one pass with extended regex (-E).

    grep -E 'error|warning|critical' /var/log/syslog

    Example: Find all error levels in logs with grep -E 'ERROR|WARN|FATAL' app.log

    Inverse Match with Line Numbers

    Show all lines that don't match a pattern, with line numbers. Useful for excluding specific entries from output.

    grep -vn 'DEBUG' application.log

    Combine: grep -v 'DEBUG' log | grep -v 'INFO' | grep -n 'ERROR'