## Search text for lines matching patterns

# Search for a word in a file
grep "error" /var/log/syslog

# Case-insensitive search
grep -i "warning" app.log

# Recursive search in a directory
grep -r "TODO" src/

# Recursive with line numbers
grep -rn "def main" .

# Only print names of files that match
grep -rl "API_KEY" .

# Only print names of files that do NOT match
grep -L "license" *.py

# Invert match: lines that do NOT contain the pattern
grep -v "^#" /etc/ssh/sshd_config

# Show config without comments and empty lines
grep -Ev "^\s*(#|$)" /etc/nginx/nginx.conf

# Match whole words only
grep -w "port" config.ini

# Match the whole line exactly
grep -x "PermitRootLogin no" /etc/ssh/sshd_config

# Count matching lines
grep -c " 404 " /var/log/nginx/access.log

# Extended regex: several alternatives
grep -E "error|fatal|critical" app.log

# Several patterns with -e
grep -e "timeout" -e "connection refused" app.log

# Fixed string, no regex (fast, dots are literal)
grep -F "user.name[0]" data.txt

# Read patterns from a file
grep -f blocked_ips.txt /var/log/nginx/access.log

# Print only the matching part
grep -oE "[0-9]+ms" app.log

# Top 10 IP addresses in an access log
grep -oE "([0-9]{1,3}\.){3}[0-9]{1,3}" access.log | sort | uniq -c | sort -rn | head

# Perl regex: extract the value after user=
grep -oP "(?<=user=)\w+" auth.log

# Show 3 lines after each match
grep -A 3 "Traceback" app.log

# Show 2 lines before each match
grep -B 2 "Killed process" /var/log/kern.log

# Show 5 lines around each match
grep -C 5 "OutOfMemoryError" app.log

# Search only in certain file types
grep -rn --include="*.py" "import requests" .

# Exclude directories from the search
grep -rn --exclude-dir={node_modules,.git,venv} "console.log" .

# Stop after the first 5 matches
grep -m 5 "ERROR" app.log

# Lines that start with / end with a pattern
grep "^Sep 30" /var/log/syslog
grep "\.conf$" files.txt

# Keep colors when paging through results
grep --color=always "error" app.log | less -R

# Find a process without matching the grep itself
ps aux | grep "[n]ginx"

# Quiet mode for scripts: only the exit code matters
grep -q "^merab:" /etc/passwd && echo "user exists"

# Search inside gzip-compressed logs
zgrep "error" /var/log/syslog.2.gz

# Always print the file name with each match
grep -H "server_name" /etc/nginx/sites-enabled/*

# Filter a live log
tail -f /var/log/nginx/access.log | grep --line-buffered " 500 "

# Find files with a string and replace it in all of them
grep -rlZ "old.example.com" . | xargs -0 sed -i 's/old.example.com/new.example.com/g'
