copied to clipboard!
string grep

Mastering grep Context: The Ultimate Guide to Displaying Surrounding Lines

updated: 2026/06/10 created: 2026/06/10

Introduction

grep is a representative command for string searching in Linux and Unix environments.

However, if you only check the matching lines, you cannot understand the surrounding context, which can make troubleshooting time-consuming.

This is where the context display feature comes in handy.

This article covers everything from the basics of grep context, how to use the -A, -B, and -C options, combining them with line number and color display, to log analysis and performance improvements.

Reference: GNU grep

Basics of grep Context

Creating the File

cat << 'EOF' > input.txt error: connection failed info: retry started warning: timeout detected error: authentication failed info: process completed EOF

Command

grep -C 1 "error" input.txt

Output

error: connection failed
info: retry started
warning: timeout detected
error: authentication failed
info: process completed

Command

grep -B 1 "error" input.txt

Output

error: connection failed
--
warning: timeout detected
error: authentication failed

Command

grep -A 1 "error" input.txt

Output

error: connection failed
info: retry started
--
error: authentication failed
info: process completed

How It Works

Option Meaning Example
-C N Display N lines before and after the matching line grep -C 1 "error" input.txt
-B N Display N lines before the matching line grep -B 1 "error" input.txt
-A N Display N lines after the matching line grep -A 1 "error" input.txt
-- Separator line between distant contexts Displayed when using -A or -C

Explanation

Using grep's context feature lets you view not only the line matching the search keyword, but also the surrounding related lines.
This is especially useful for log analysis and configuration file investigation.

How to Use the -A Option to Display grep Context

Creating the File

cat << 'EOF' > input.txt INFO: Application started INFO: Loading configuration ERROR: Database connection failed INFO: Retrying connection INFO: Connection retry failed WARN: Switching to fallback mode INFO: Fallback mode enabled ERROR: Cache server unavailable INFO: Processing request INFO: Request completed EOF

Command

grep -A 2 "ERROR" input.txt

Output

ERROR: Database connection failed
INFO: Retrying connection
INFO: Connection retry failed
--
ERROR: Cache server unavailable
INFO: Processing request
INFO: Request completed

How It Works

Item Description
grep A command that searches for lines matching a pattern
-A 2 Displays 2 lines after (After) the matching line
Context Related information surrounding the matching line
-- A separator that divides multiple match results
Use case When you want to check what happens after an error log occurs

Explanation

Using the -A option lets you see not only the matching line but also the subsequent related log entries.

This is useful when you want to understand the context around a match during log analysis or incident investigation.

How to Use the -B Option to Display grep Context

Creating the File

cat << 'EOF' > input.txt ERROR: Connection failed INFO: Retrying connection WARN: Slow response detected ERROR: Authentication failed INFO: User logged in ERROR: Database timeout INFO: Process completed EOF

Command

grep -B 2 "ERROR" input.txt

Output

ERROR: Connection failed
INFO: Retrying connection
WARN: Slow response detected
ERROR: Authentication failed
INFO: User logged in
ERROR: Database timeout

How It Works

Item Description
grep A command that searches for a specified string
-B 2 Displays the 2 lines before the matching line as context
"ERROR" The string to search for
input.txt The file to search
-- A separator to divide multiple search results

Explanation

Using the grep -B option lets you check the context surrounding search results.
This is a convenient grep context display feature for investigating the state of a system before an error occurred during log analysis.

How to Use the -C Option to Display grep Context

Creating the File

cat << 'EOF' > input.txt 001: start 002: initialize 003: load config 004: connect database 005: authentication 006: search target 007: fetch records 008: process data 009: save result 010: end EOF

Command

grep -C 2 "search target" input.txt

Output

004: connect database
005: authentication
006: search target
007: fetch records
008: process data

Command

grep -C 1 "search target" input.txt

Output

005: authentication
006: search target
007: fetch records

Command

grep -C 3 "search target" input.txt

Output

003: load config
004: connect database
005: authentication
006: search target
007: fetch records
008: process data
009: save result

How It Works

Item Description
grep A command that searches for a specified string
-C N Displays N lines before and after the matching line
Matching line The line containing the search keyword
Surrounding lines Lines displayed as context
Use case Allows you to check surrounding information at the same time when analyzing logs or configuration files

Explanation

Using the grep -C option lets you view not only the matching line but also the related lines before and after it.

This is useful when you want to understand the context of search results while investigating logs or configuration files.

How to Adjust the Context Range by Changing the Number of Lines in grep

Creating the File

cat << 'EOF' > input.txt INFO: application started INFO: loading configuration ERROR: database connection failed INFO: retrying connection INFO: retry attempt 1 INFO: retry attempt 2 ERROR: database connection failed INFO: sending alert INFO: application stopped EOF

Command

grep -C 1 "ERROR" input.txt

Output

INFO: loading configuration
ERROR: database connection failed
INFO: retrying connection
--
INFO: retry attempt 2
ERROR: database connection failed
INFO: sending alert

Command

grep -C 2 "ERROR" input.txt

Output

INFO: application started
INFO: loading configuration
ERROR: database connection failed
INFO: retrying connection
INFO: retry attempt 1
INFO: retry attempt 2
ERROR: database connection failed
INFO: sending alert
INFO: application stopped

Command

grep -B 2 "ERROR" input.txt

Output

INFO: application started
INFO: loading configuration
ERROR: database connection failed
--
INFO: retry attempt 1
INFO: retry attempt 2
ERROR: database connection failed

Command

grep -A 2 "ERROR" input.txt

Output

ERROR: database connection failed
INFO: retrying connection
INFO: retry attempt 1
--
ERROR: database connection failed
INFO: sending alert
INFO: application stopped

How It Works

Option Meaning Example Output
-C N Display N lines before and after grep -C 2 "ERROR" input.txt 2 lines before and after the matching line
-B N Display N lines before the matching line grep -B 2 "ERROR" input.txt 2 lines before the matching line
-A N Display N lines after the matching line grep -A 2 "ERROR" input.txt 2 lines after the matching line

Explanation

The number of lines displayed by grep's context feature can be changed with the -C, -B, and -A options.
This is useful when you want to check the surrounding state during log analysis.

How to Display grep Context and Line Numbers Simultaneously

Creating the File

cat << 'EOF' > input.txt INFO: Start application DEBUG: Load config ERROR: Connection failed INFO: Retry connection ERROR: Timeout occurred INFO: End application EOF

Command

grep -n -C 1 "ERROR" input.txt

Output

2-DEBUG: Load config
3:ERROR: Connection failed
4-INFO: Retry connection
5:ERROR: Timeout occurred
6-INFO: End application

Command

grep -n -B 1 -A 2 "ERROR" input.txt

Output

2-DEBUG: Load config
3:ERROR: Connection failed
4-INFO: Retry connection
5:ERROR: Timeout occurred
6-INFO: End application

How It Works

Option Description
-n Displays the line number of matching lines
-C N Displays N lines of context before and after
-B N Displays N lines before the matching line
-A N Displays N lines after the matching line
-- Displays a separator between distant match results

Explanation

In grep, combining -n and -C lets you check both line numbers and context at the same time.
This is useful when you want to quickly grasp the context around matching lines during incident investigation or log analysis.

How to Highlight Only Matching Lines in grep Context Search

Creating the File

cat << 'EOF' > input.txt INFO: application started ERROR: database connection failed INFO: retrying connection INFO: connection established ERROR: timeout occurred INFO: application finished EOF

Command

grep --color=always -C 1 "ERROR" input.txt

Output

INFO: application started
ERROR: database connection failed
INFO: retrying connection
INFO: connection established
ERROR: timeout occurred
INFO: application finished

Command

grep --color=always -B 1 -A 1 "ERROR" input.txt

Output

INFO: application started
ERROR: database connection failed
INFO: retrying connection
INFO: connection established
ERROR: timeout occurred
INFO: application finished

How It Works

Option Description
--color=always Highlights only the matching string in color
-C 1 Displays 1 line before and after the matching line as context
-B 1 Displays 1 line before the matching line
-A 1 Displays 1 line after the matching line
"ERROR" The string to search for
input.txt The file to search

Explanation

In grep context search, you can display surrounding lines using -C or -A -B.
Combined with --color=always, the context lines are shown as-is while only the matching string within the matching line is highlighted.

How to Improve Readability by Combining grep Context with Color Display

Creating the File

cat << 'EOF' > input.txt [INFO] Application started [INFO] Loading configuration [WARN] Deprecated setting detected [INFO] Connecting to database [ERROR] Database connection failed [INFO] Retrying connection [INFO] Connecting to database [ERROR] Authentication failed [INFO] Sending alert [INFO] Application terminated EOF

Command

grep --color=always -C 2 "ERROR" input.txt

Output

[WARN] Deprecated setting detected
[INFO] Connecting to database
[ERROR] Database connection failed
[INFO] Retrying connection
[INFO] Connecting to database
[ERROR] Authentication failed
[INFO] Sending alert
[INFO] Application terminated

Command

grep --color=always -B 2 -A 1 "ERROR" input.txt

Output

[WARN] Deprecated setting detected
[INFO] Connecting to database
[ERROR] Database connection failed
[INFO] Retrying connection
[INFO] Connecting to database
[ERROR] Authentication failed
[INFO] Sending alert

How It Works

Option Description
--color=always Highlights the search keyword in color
-C 2 Displays 2 lines before and after the matching line
-B 2 Displays 2 lines before the matching line
-A 1 Displays 1 line after the matching line
"ERROR" The string to search for
input.txt The file to search

Explanation

Using grep's context display lets you review the flow around an error occurrence all at once.
Combining it with --color highlights the matching line, improving readability during log analysis.

How to Combine grep Context with Multi-Keyword Search

Creating the File

cat << 'EOF' > input.txt 2024-01-01 INFO Application started 2024-01-01 ERROR Database connection failed 2024-01-01 INFO Retry database connection 2024-01-01 WARN Database response slow 2024-01-01 ERROR User authentication failed 2024-01-01 INFO User retry login 2024-01-01 ERROR Database timeout occurred 2024-01-01 INFO Service stopped EOF

Command

grep -E -B 1 -A 1 'ERROR.*Database|Database.*ERROR' input.txt

Output

2024-01-01 INFO Application started
2024-01-01 ERROR Database connection failed
2024-01-01 INFO Retry database connection
--
2024-01-01 INFO User retry login
2024-01-01 ERROR Database timeout occurred
2024-01-01 INFO Service stopped

Command

grep -E -C 1 'ERROR.*Database|Database.*ERROR' input.txt

Output

2024-01-01 INFO Application started
2024-01-01 ERROR Database connection failed
2024-01-01 INFO Retry database connection
--
2024-01-01 INFO User retry login
2024-01-01 ERROR Database timeout occurred
2024-01-01 INFO Service stopped

How It Works

Item Description
grep Searches text for lines matching specified conditions
-E Enables extended regular expressions
ERROR.*Database|Database.*ERROR Searches for lines containing both ERROR and Database
-A 1 Displays 1 line after the matching line
-B 1 Displays 1 line before the matching line
-C 1 Displays 1 line before and after the matching line together
-- Indicates the separator between distant search results

Explanation

grep's context options (-A, -B, -C) can be combined with multi-keyword search to check the context around matching lines.

This allows you to efficiently investigate the state before and after an error during log analysis.

How to Use grep Context with Regular Expression Search

Creating the File

cat << 'EOF' > input.txt INFO: Application started DEBUG: Loading configuration ERROR: Database connection failed DEBUG: Retrying connection INFO: Retry attempt 1 ERROR: Authentication failed DEBUG: Sending alert INFO: Application stopped EOF

Command

grep -E -B 1 -A 2 'ERROR|Authentication' input.txt

Output

DEBUG: Loading configuration
ERROR: Database connection failed
DEBUG: Retrying connection
INFO: Retry attempt 1
ERROR: Authentication failed
DEBUG: Sending alert
INFO: Application stopped

Command

grep -E -C 1 'ERROR.*failed' input.txt

Output

DEBUG: Loading configuration
ERROR: Database connection failed
DEBUG: Retrying connection
INFO: Retry attempt 1
ERROR: Authentication failed
DEBUG: Sending alert

How It Works

Option Role Relationship to grep Context
-E Use extended regular expressions Allows writing patterns like ERROR|Authentication or ERROR.*failed
-A n Display n lines after a match Used to check the state of subsequent processing
-B n Display n lines before a match Used to check the state before an error occurred
-C n Display n lines before and after Check surrounding information all at once
ERROR.*failed Regular expression search Matches even when there are arbitrary characters between ERROR and failed

Explanation

Using grep's context options (-A, -B, -C) lets you see not only the lines matching a regular expression but also the related logs before and after. This is effective for quickly identifying the cause and scope of impact during incident analysis or log investigation.

How to Exclude Unnecessary Lines When Displaying grep Context

Creating the File

cat << 'EOF' > input.txt INFO start ERROR database connection failed detail retry=1 detail retry=2 INFO healthcheck ERROR disk full detail path=/data INFO end EOF

Command

grep -A2 "ERROR" input.txt

Output

ERROR database connection failed
detail retry=1
detail retry=2
--
ERROR disk full
detail path=/data
INFO end

Command

grep -A2 "ERROR" input.txt | grep -v '^--$'

Output

ERROR database connection failed
detail retry=1
detail retry=2
ERROR disk full
detail path=/data
INFO end

How It Works

Item Description
grep -A2 Displays 2 lines after the matching line as context
-- Automatically output by grep as a separator between multiple match results
grep -v '^--$' Excludes only the separator line --
-v Displays lines that do not match the pattern (exclusion)
^--$ A regular expression that matches only when the entire line is --

Explanation

With grep's context display (-A, -B, -C), a separator line -- is output between result groups.
When it is not needed, it can be easily excluded by piping through grep -v '^--$'.

How to Use grep Context with Pipe Processing

Creating the File

cat << 'EOF' > input.txt INFO: application start INFO: loading config ERROR: database connection failed INFO: retrying connection INFO: connection established WARN: high memory usage ERROR: timeout occurred INFO: request completed EOF

Command

grep -A2 "ERROR" input.txt | grep "INFO"

Output

INFO: retrying connection
INFO: connection established
INFO: request completed

How It Works

Item Description
grep -A2 "ERROR" Outputs the line matching ERROR and the following 2 lines as context
Pipe (|) Passes the result of the first grep to the second grep
grep "INFO" Extracts only lines containing INFO from the context
Use case Allows narrowing down only the relevant information from logs around an error

Explanation

Combining grep's context options (-A, -B, -C) with pipe processing lets you extract only the necessary information while preserving the surrounding context.
This is a particularly effective technique for log analysis and incident investigation.

How to Monitor Real-Time Logs by Combining grep Context with tail

Creating the File

cat << 'EOF' > input.txt 2026-06-05 10:00:01 INFO Application started 2026-06-05 10:00:02 INFO Loading configuration 2026-06-05 10:00:03 ERROR Database connection failed 2026-06-05 10:00:04 INFO Retrying connection 2026-06-05 10:00:05 INFO Connection established 2026-06-05 10:00:06 WARN High memory usage 2026-06-05 10:00:07 ERROR API timeout 2026-06-05 10:00:08 INFO Request completed EOF

Command

tail -f input.txt | grep -A 1 -B 1 "ERROR"

Output

2026-06-05 10:00:02 INFO Loading configuration
2026-06-05 10:00:03 ERROR Database connection failed
2026-06-05 10:00:04 INFO Retrying connection
--
2026-06-05 10:00:06 WARN High memory usage
2026-06-05 10:00:07 ERROR API timeout
2026-06-05 10:00:08 INFO Request completed

How It Works

Item Description
tail -f Monitors file additions in real time
grep Extracts lines containing the specified string (ERROR)
-B 1 Displays 1 line before the matching line
-A 1 Displays 1 line after the matching line
grep context Allows checking the state before and after an error at the same time
Combined effect Enables real-time display of errors and their surrounding context while monitoring log additions

Explanation

Combining tail -f with grep's context options (-A, -B) lets you check not only error lines but also the related logs before and after them.

This is a commonly used method for root cause investigation and incident analysis during real-time monitoring.

How to Identify the Root Cause in Error Logs Using grep Context

Creating the File

cat << 'EOF' > input.txt 2026-06-05 10:00:01 INFO Application started 2026-06-05 10:00:05 INFO Connecting to database 2026-06-05 10:00:08 WARN Connection timeout detected 2026-06-05 10:00:09 ERROR Database connection failed 2026-06-05 10:00:10 ERROR Retry process started 2026-06-05 10:00:12 INFO Retry succeeded 2026-06-05 10:00:15 INFO Processing request EOF

Command

grep -C 2 "ERROR" input.txt

Output

2026-06-05 10:00:05 INFO Connecting to database
2026-06-05 10:00:08 WARN Connection timeout detected
2026-06-05 10:00:09 ERROR Database connection failed
2026-06-05 10:00:10 ERROR Retry process started
2026-06-05 10:00:12 INFO Retry succeeded
2026-06-05 10:00:15 INFO Processing request

Command

grep -B 2 "ERROR" input.txt

Output

2026-06-05 10:00:05 INFO Connecting to database
2026-06-05 10:00:08 WARN Connection timeout detected
2026-06-05 10:00:09 ERROR Database connection failed
2026-06-05 10:00:10 ERROR Retry process started

Command

grep -A 2 "ERROR" input.txt

Output

2026-06-05 10:00:09 ERROR Database connection failed
2026-06-05 10:00:10 ERROR Retry process started
2026-06-05 10:00:12 INFO Retry succeeded
2026-06-05 10:00:15 INFO Processing request

How It Works

Option Meaning Use case
-C 2 Display 2 lines before and after Check the overall flow around an error
-B 2 Display 2 lines before Identify the processing that caused the error
-A 2 Display 2 lines after Check the impact or recovery processing after an error
"ERROR" Search pattern Extract only error logs

Explanation

Using grep's context options (-A, -B, -C) lets you check not only the error line but also the related logs before and after it.

How to Use grep Context for Large-Scale Log Analysis

Creating the File

cat << 'EOF' > input.txt 2026-06-01 10:00:01 INFO Application started 2026-06-01 10:00:05 INFO Loading configuration 2026-06-01 10:00:08 WARN Response time exceeded threshold 2026-06-01 10:00:10 INFO Health check passed 2026-06-01 10:00:15 ERROR Database connection timeout 2026-06-01 10:00:18 INFO Retrying connection 2026-06-01 10:00:22 ERROR Database connection timeout 2026-06-01 10:00:25 INFO Retrying connection 2026-06-01 10:00:30 INFO Connection established 2026-06-01 10:00:35 INFO Processing requests EOF

Command

grep -C 2 "ERROR" input.txt

Output

2026-06-01 10:00:08 WARN Response time exceeded threshold
2026-06-01 10:00:10 INFO Health check passed
2026-06-01 10:00:15 ERROR Database connection timeout
2026-06-01 10:00:18 INFO Retrying connection
2026-06-01 10:00:22 ERROR Database connection timeout
2026-06-01 10:00:25 INFO Retrying connection
2026-06-01 10:00:30 INFO Connection established

Command

grep -B 3 "ERROR" input.txt

Output

2026-06-01 10:00:05 INFO Loading configuration
2026-06-01 10:00:08 WARN Response time exceeded threshold
2026-06-01 10:00:10 INFO Health check passed
2026-06-01 10:00:15 ERROR Database connection timeout
2026-06-01 10:00:18 INFO Retrying connection
2026-06-01 10:00:22 ERROR Database connection timeout

Command

grep -A 2 "ERROR" input.txt

Output

2026-06-01 10:00:15 ERROR Database connection timeout
2026-06-01 10:00:18 INFO Retrying connection
2026-06-01 10:00:22 ERROR Database connection timeout
2026-06-01 10:00:25 INFO Retrying connection
2026-06-01 10:00:30 INFO Connection established

How It Works

Option Name How It Works Use case
-C N Before/After Context Displays N lines before and after the matching line Check the overall flow around an error
-B N Before Displays N lines before the matching line Investigate the cause of an incident
-A N After Displays N lines after the matching line Check retry or recovery processing after an error

Explanation

In large-scale log analysis, combining context display with simple error extraction allows you to efficiently grasp the cause and scope of impact.

Using grep context lets you check the surrounding context without needing additional log viewing commands.

How to Improve Performance in grep Context Search

Creating the File

cat << 'EOF' > input.txt INFO start process INFO connect database ERROR timeout occurred INFO retry connection INFO connect database ERROR authentication failed INFO shutdown process EOF

Command

LC_ALL=C grep -n -C 1 "ERROR" input.txt

Output

2-INFO connect database
3:ERROR timeout occurred
4-INFO retry connection
5-INFO connect database
6:ERROR authentication failed
7-INFO shutdown process

Command

LC_ALL=C grep -F -n -C 1 "ERROR" input.txt

Output

2-INFO connect database
3:ERROR timeout occurred
4-INFO retry connection
5-INFO connect database
6:ERROR authentication failed
7-INFO shutdown process

Command

LC_ALL=C grep -F -n -A 1 -B 1 "ERROR" input.txt

Output

2-INFO connect database
3:ERROR timeout occurred
4-INFO retry connection
5-INFO connect database
6:ERROR authentication failed
7-INFO shutdown process

How It Works

Item How It Works Effect
LC_ALL=C Simplifies locale handling and searches byte by byte Reduces character processing overhead
-F Searches for fixed strings without the regular expression engine Improves search speed
-C 1 Retrieves 1 line of context before and after at once Improves log analysis efficiency
-A -B Specifies the number of lines before/after individually Reduces processing load with minimal output
-n Adds line numbers Speeds up identification of the relevant location

Explanation

For grep context search, using -F for fixed strings combined with LC_ALL=C enables fast searching even in large-scale logs.

Keeping the number of context lines to the minimum necessary also reduces output volume and processing load.

Summary of Key Points for Using grep Context

Using grep's context feature lets you understand the surrounding context that matching lines alone cannot reveal.

By using the -A, -B, and -C options appropriately, you can efficiently retrieve the information you need, and combining them with line number display and color display further improves readability.

By understanding grep's context feature, you will be able to perform faster and more accurate work, from everyday log checking to large-scale incident investigation.

Leave a Reply

Your email address will not be published. Required fields are marked *

©︎ 2025-2026 running terminal commands