💻
🔧
🐧
Intermediate
Bash
July 8, 2025

Linux Grep Command: Advanced Text Search with Context Lines

Categories: Command Line
Tags: #grep

Description

How to Use Linux Grep Command with Context Lines?

Quick Answer: Use grep -A 3 -B 3 "pattern" file to show 3 lines after and before each match, providing crucial context for log analysis and debugging. Add -r for recursive searching and -n for line numbers.

Frequently Asked Questions

Q: What does grep -A and -B mean? A: -A shows lines After the match, -B shows lines Before the match. grep -A 5 -B 3 "error" shows 5 lines after and 3 lines before each match.

Q: How do I show the same number of lines before and after? A: Use -C (context) followed by a number. grep -C 4 "pattern" shows 4 lines both before and after each match.

Q: Can I use grep context with recursive search? A: Yes, combine -r with context options: grep -r -A 3 -B 3 "ERROR" /var/log searches all files recursively with context.

Q: How do I limit grep context search to specific file types? A: Use --include with patterns: grep -r -A 5 --include="*.log" "ERROR" /var/log searches only .log files.

Q: What’s the difference between -A 3 -B 3 and -C 3? A: They’re equivalent. -C 3 is shorthand for -A 3 -B 3, both show 3 lines before and after matches.

Essential Steps to Use Grep with Context Lines

  1. Start with basic context: Use grep -C 3 "pattern" file to see 3 lines before and after matches
  2. Add line numbers: Include -n option like grep -n -C 3 "ERROR" logfile for easier navigation
  3. Make it recursive: Add -r to search directories: grep -r -C 5 "pattern" /var/log
  4. Limit file types: Use --include="*.log" to search only specific file extensions
  5. Add colors for clarity: Include --color=always to highlight matches in output
  6. Combine with output redirection: Save results with grep -r -C 3 "ERROR" /var/log > analysis.txt

Essential Grep Context Commands

The linux grep command with context lines transforms basic pattern searching into comprehensive text analysis. Context lines reveal surrounding information that makes troubleshooting and log analysis significantly more effective.

Basic Context Syntax

grep -A [after] -B [before] "pattern" file
grep -C [both] "pattern" file  # Same number before and after

Step-by-Step Context Line Usage

1. Show Lines After Match (-A)

# Show 5 lines after each ERROR
grep -A 5 "ERROR" /var/log/syslog

2. Show Lines Before Match (-B)

# Show 3 lines before each FATAL error
grep -B 3 "FATAL" /var/log/application.log

3. Show Lines Before and After (-A and -B)

# Show 3 lines before and 5 lines after
grep -A 5 -B 3 "database connection failed" /var/log/mysql.log

4. Symmetric Context (-C)

# Show 4 lines both before and after
grep -C 4 "authentication failed" /var/log/auth.log

Most Used Grep Context Commands

CommandPurposeExample Output
grep -A 3 "ERROR" file.logShow 3 lines after matchShows error + next 3 lines
grep -B 2 "FATAL" file.logShow 2 lines before matchShows previous 2 lines + fatal error
grep -C 5 "warning" file.logShow 5 lines both sidesShows 5 before + match + 5 after
grep -r -A 3 "failed" /var/logRecursive search with contextSearches all files with 3 lines after
grep -n -C 2 "timeout" file.logLine numbers with contextShows line numbers and 2 lines context

Advanced Grep Context Examples

Recursive Search with Context

# Search all log files recursively with context
grep -r -n -A 3 -B 3 --color=always "ERROR" /var/log

# Multiple file types with context
grep -r -n -A 5 -B 5 --include="*.log" "Failed" /var/log

Professional Troubleshooting Commands

# Extended context for complex analysis
grep -r -n -A 10 -B 5 --color=always -i "authentication.*failed" /var/log

# Multiple patterns with context
grep -r -n -A 3 -B 3 --include="*.{log,conf,txt}" -E "(error|warning|critical)" /var

# Time-based filtering with context
grep -r -n -A 3 -B 3 "$(date '+%Y-%m-%d')" /var/log | grep -i error

Common Use Cases

Server Crash Investigation

grep -r -n -A 5 -B 5 "segmentation fault" /var/log

Authentication Failures

grep -r -n -A 3 -B 3 "Failed login" /var/log

Database Connection Issues

grep -r -n -A 4 -B 2 "database.connection.failed" /var/log

Memory Issues

grep -r -n -A 10 -B 5 "Out of memory" /var/log

Essential Context Options

OptionDescriptionExample
-A 55 lines aftergrep -A 5 "ERROR" file.log
-B 33 lines beforegrep -B 3 "FATAL" file.log
-C 44 lines both sidesgrep -C 4 "WARN" file.log
-rRecursive searchgrep -r -A 3 "pattern" /path
-nShow line numbersgrep -n -A 2 "error" file.log

Performance and Security Tips

Performance optimization:

  • Use --include and --exclude to limit file types
  • Specify exact paths instead of broad recursive searches
  • Combine with head or tail for large files

Security considerations:

  • Be cautious with recursive grep on sensitive directories
  • Use specific paths to avoid scanning confidential files
  • Consider using sudo only when necessary

Why Context Lines Matter

Context lines provide essential benefits for system administrators and developers:

  • Enhanced log analysis – See what happened before and after errors
  • Improved debugging – Understand code/config relationships around issues
  • Security investigation – Get timeline context from log entries
  • Configuration validation – See setting relationships and dependencies
  • Performance analysis – View metrics context surrounding alerts

Related Commands for Text Analysis

  • awk – Advanced text processing and field extraction
  • sed – Stream editor for filtering and transforming text
  • tail -f – Real-time log monitoring with context
  • less – Paginated viewing with search capabilities
  • sort and uniq – Organize and filter results

Advanced Automation Workflows

Save Context Analysis to File

# Redirect context search results for analysis
grep -r -n -A 5 -B 2 "segmentation fault" /var/log > /tmp/crash_analysis.txt

Combine with Other Tools

# Chain grep with other commands for comprehensive analysis
grep -r -A 3 -B 3 "ERROR" /var/log | sort | uniq -c | sort -nr

Mastering grep with context lines transforms your text analysis from basic pattern matching to comprehensive contextual investigation, making it an indispensable tool for effective system troubleshooting and log analysis.

Detailed Explanation

🔍 Command Breakdown: grep Base command for searching text patterns in files Acronym for "Global Regular Expression Print" -r (recursive) Recursive search through all subdirectories Scans /var/log and every folder within it Without -r it would only search in the specified directory -n (line numbers) Shows line numbers where matches are found Example output: file.log:145:ERROR message here The 145 is the line number in the file -A 3 (After context) Shows 3 lines AFTER each match found Provides context of what happens after the error Useful for seeing consequences or related messages -B 3 (Before context) Shows 3 lines BEFORE each match found Provides context of what caused the error Helps understand the sequence of events --color=always Highlights in color the found pattern ("ERROR") always forces coloring even when output is redirected Makes it easier to visually identify matches "ERROR" Pattern to search - the exact string "ERROR" Quotes prevent shell interpretation Case-sensitive (searches exactly "ERROR", not "error") /var/log Search directory - typical location for system logs Contains logs from Apache, MySQL, system, kernel, etc. 📊 Example Output: bash/var/log/apache2/error.log-145-[Wed Oct 25 10:30:15.123456 2023] info /var/log/apache2/error.log-146-[Wed Oct 25 10:30:16.234567 2023] warning /var/log/apache2/error.log-147-[Wed Oct 25 10:30:17.345678 2023] notice /var/log/apache2/error.log:148:[Wed Oct 25 10:30:18.456789 2023] ERROR Database connection failed /var/log/apache2/error.log+149+[Wed Oct 25 10:30:19.567890 2023] Retrying connection... /var/log/apache2/error.log+150+[Wed Oct 25 10:30:20.678901 2023] Connection restored /var/log/apache2/error.log+151+[Wed Oct 25 10:30:21.789012 2023] Request processed 🔧 Output Explanation: -145-, -146-, -147- = 3 lines BEFORE the match (-B 3) :148: = line with the exact match (ERROR) +149+, +150+, +151+ = 3 lines AFTER the match (-A 3) 148 = line number in the file (-n) 💡 Why It's Useful: Complete troubleshooting - see what caused the error and what happened after Timeline analysis - understand the sequence of events Context awareness - not just the problem, but also the surrounding context Efficiency - one command for comprehensive search Pro Tips: Combine with tail -f for real-time monitoring Pipe to less for paginated output: grep ... | less Save results for analysis: grep ... > error_analysis.txt Use --exclude-dir to skip certain directories Add timestamps with --color=always for better visibility This command is particularly powerful for incident response and log analysis!

Related Commands