Introduction
grep is a command frequently used for text searching.
The line number display feature is especially useful when you want to confirm which line a search result appears on.
This article explains everything from the basic syntax for displaying line numbers with grep to advanced usage.
Reference: GNU grep
Basic Syntax for Displaying Line Numbers with grep
Create File
cat << 'EOF' > input.txt
apple
banana
grape
banana smoothie
orange
EOF
Command
grep -n "banana" input.txt
Output
2:banana
4:banana smoothie
How It Works
| Item | Description |
|---|---|
| grep | Searches for the specified string |
| -n | Displays the line number at the beginning of each matching line |
| "banana" | The string to search for |
| input.txt | The file to search |
Explanation
Using grep -n displays line numbers along with the search results.
This is useful when you want to quickly locate the relevant section in a configuration file or log file.
Displaying grep Search Results with Line Numbers and Filename
Create File
cat << 'EOF' > input.txt
apple
banana
orange
apple juice
grape
EOF
Command
grep -nH "apple" input.txt
Output
input.txt:1:apple
input.txt:4:apple juice
How It Works
| Option | Description |
|---|---|
| grep | Command that searches for the specified string |
| -n | Displays the line number of each matching line |
| -H | Displays the filename at the beginning of each search result |
| "apple" | Search keyword |
| input.txt | File to search |
Explanation
Using grep -nH displays both the line number and filename alongside the search results.
When searching multiple files, this lets you quickly identify which file and which line number a match was found on.
Listing Line Numbers Across Multiple Files with grep
Create File
cat << 'EOF' > file1.txt
apple
banana
orange
banana
EOF
Create File
cat << 'EOF' > file2.txt
grape
banana
melon
EOF
Create File
cat << 'EOF' > file3.txt
banana
peach
banana
EOF
Command
grep -n "banana" file1.txt
Output
2:banana
4:banana
Command
grep -n "banana" file2.txt
Output
2:banana
Command
grep -n "banana" file3.txt
Output
1:banana
3:banana
Command
grep -n "banana" file*.txt
Output
file1.txt:2:banana
file1.txt:4:banana
file2.txt:2:banana
file3.txt:1:banana
file3.txt:3:banana
How It Works
| Item | Description |
|---|---|
| grep | Command for text searching |
| -n | Option to display the line number of each matching line |
| file*.txt | Specifies file1.txt, file2.txt, and file3.txt together |
| Output format | filename:line number:matching line |
| Use case | Checking the location of a target string across multiple files at once |
Explanation
Using grep -n lets you see the line numbers of matching strings.
When multiple files are specified at once, the filename and line number are both shown, making it easy to quickly locate the relevant section.
Recursive Directory Search with Line Numbers Using grep
Create File
cat << 'EOF' > input.txt
src/main.py:10:def main():
src/main.py:25:print("hello")
src/utils/helper.py:8:def helper():
docs/readme.md:15:How to use grep
logs/app.log:100:ERROR failed
EOF
Create File
mkdir -p src/utils docs logs
Create File
awk -F: '{print $2 ":" $3}' input.txt > src/main.py
Create File
awk -F: 'NR==3{print $2 ":" $3}' input.txt > src/utils/helper.py
Create File
awk -F: 'NR==4{print $2 ":" $3}' input.txt > docs/readme.md
Create File
awk -F: 'NR==5{print $2 ":" $3}' input.txt > logs/app.log
Command
grep -rn "grep" .
Output
src/main.py:4:15:How to use grep
docs/readme.md:1:15:How to use grep
Command
grep -rn "def" .
Output
src/utils/helper.py:1:8:def helper()
src/main.py:1:10:def main()
src/main.py:3:8:def helper()
How It Works
| Item | Description |
|---|---|
| grep | Command for searching text |
| -r | Recursively searches within a directory |
| -n | Displays the line number of each matching line |
| "grep" | The string to search for |
| . | Searches within the current directory and below |
Explanation
Using grep -rn lets you recursively search within a directory while displaying the line number of each matching line.
This is commonly used for source code investigation and configuration file searches.
Displaying Line Numbers Only for Exact Word Matches with grep
Create File
cat << 'EOF' > input.txt
apple
banana
orange
apple pie
grape
apple
EOF
Command
grep -nx "apple" input.txt
Output
1:apple
6:apple
How It Works
| Option | Description |
|---|---|
| grep | Searches for the specified string |
| -n | Displays the line number of each matching line |
| -x | Matches only when the entire line exactly matches the search string |
| "apple" | The string to search for |
| input.txt | File to search |
Explanation
Using -x excludes partial matches like "apple pie" and targets only lines that exactly match "apple".
Combining with -n lets you confirm only the line numbers of matching lines.
Case-Insensitive Search with Line Numbers Using grep
Create File
cat << 'EOF' > input.txt
Apple
banana
APPLE
Orange
apple pie
EOF
Command
grep -in "apple" input.txt
Output
1:Apple
3:APPLE
5:apple pie
How It Works
| Option | Description |
|---|---|
| grep | Searches for lines containing the specified string |
| -i | Searches without distinguishing between uppercase and lowercase |
| -n | Displays the line number of each matching line |
| "apple" | Keyword to search for |
| input.txt | File to search |
Explanation
Using grep -in searches case-insensitively and simultaneously displays the line numbers of matching lines.
This is useful for quickly locating target lines during log analysis or configuration file inspection.
Searching for Lines Matching Specific Patterns with Line Numbers Using Regex in grep
Create File
cat << 'EOF' > input.txt
apple
banana
error: file not found
orange
warning: low disk space
grape
error: permission denied
melon
EOF
Command
grep -n '^error:' input.txt
Output
3:error: file not found
7:error: permission denied
How It Works
| Element | Description |
|---|---|
| grep | Command that searches text for lines matching a condition |
| -n | Displays the line number at the beginning of each matching line |
| ^ | Regular expression representing the start of a line |
| error: | The string to search for |
| '^error:' | Regular expression that extracts only lines beginning with "error:" |
Explanation
Using grep -n lets you simultaneously confirm matching lines and their line numbers.
Combining with regular expressions allows you to efficiently search for lines matching a specific pattern in log files and similar use cases.
Searching for Line Numbers with Multiple Keywords Using OR Conditions in grep
Create File
cat << 'EOF' > input.txt
grep is a command for string searching
sed is used for line editing
Use the -n option to display line numbers
awk can also handle line numbers
grep can search for multiple keywords
EOF
Command
grep -nE 'grep|line|number' input.txt
Output
1:grep is a command for string searching
2:sed is used for line editing
3:Use the -n option to display line numbers
4:awk can also handle line numbers
5:grep can search for multiple keywords
How It Works
| Element | Description |
|---|---|
| grep | Text search command |
| -n | Displays the line number at the beginning of each matching line |
| -E | Enables extended regular expressions |
| grep|line|number | OR condition (grep or line or number) |
| input.txt | File to search |
Explanation
Using grep -nE lets you search with multiple keywords joined by | as OR conditions.
Matching lines are assigned line numbers, allowing you to quickly locate the relevant sections.
Searching for Line Numbers with Multiple Keywords Using AND Conditions in grep
Create File
cat << 'EOF' > input.txt
Basic usage of grep
How to display line numbers with grep using -n
How to handle line numbers with awk
Example of combining grep and line numbers
Searching with multiple conditions in grep
Running a grep search with line numbers
Combining sed and grep
Sample containing grep line number
Line containing grep only
Line containing line numbers only
EOF
Command
grep -n 'grep' input.txt | grep 'line' | grep 'number'
Output
2:How to display line numbers with grep using -n
4:Example of combining grep and line numbers
6:Running a grep search with line numbers
8:Sample containing grep line number
How It Works
| Item | Description |
|---|---|
| grep -n 'grep' input.txt | Searches for lines containing "grep" and displays line numbers |
| grep 'line' | Extracts only lines containing "line" from the previous result |
| grep 'number' | Further extracts only lines containing "number" |
| Pipe (|) | Passes the output of the previous command to the next command |
| AND search | Only lines that pass all grep conditions remain |
Explanation
AND searches with multiple keywords can be achieved by chaining grep commands with pipes.
Adding the -n option lets you simultaneously confirm the line numbers of matching lines.
Displaying Line Numbers for Non-Matching Lines with grep
Create File
cat << 'EOF' > input.txt
apple
orange
banana
grape
EOF
Command
grep -vn "apple" input.txt
Output
2:orange
3:banana
4:grape
How It Works
| Option | Description |
|---|---|
| grep | Performs pattern searching |
| -v | Displays lines that do not match |
| -n | Displays the line number at the beginning of each line |
| "apple" | The search string to exclude |
| input.txt | File to search |
Explanation
The -v option in grep extracts lines that do not match the search condition, and -n displays their line numbers.
This lets you simultaneously confirm the line numbers and content of non-matching lines.
Displaying Surrounding Lines with Line Numbers Using grep
Create File
cat << 'EOF' > input.txt
apple
banana
orange
grape
banana
melon
banana
peach
EOF
Command
grep -n -B 1 -A 1 "banana" input.txt
Output
1-apple
2:banana
3-orange
4-grape
5:banana
6-melon
7:banana
8-peach
Command
grep -n -C 2 "banana" input.txt
Output
1-apple
2:banana
3-orange
4-grape
5:banana
6-melon
7:banana
8-peach
How It Works
| Option | Description |
|---|---|
| -n | Displays the line number of each matching line |
| -B <num> | Displays the specified number of lines before each matching line |
| -A <num> | Displays the specified number of lines after each matching line |
| -C <num> | Displays the specified number of lines before and after each matching line |
Explanation
Using grep's -n option lets you confirm the line numbers of matching lines.
Combining with -A, -B, and -C also lets you view the surrounding context of matching lines.
Getting the Line Number of the First Match with grep
Create File
cat << 'EOF' > input.txt
apple
banana
orange
banana smoothie
grape
EOF
Command
grep -nm1 "banana" input.txt
Output
2:banana
Command
grep -nm1 "banana" input.txt | cut -d: -f1
Output
2
How It Works
| Item | Description |
|---|---|
| grep | Searches for lines matching a pattern |
| -n | Displays the line number of each matching line |
| -m1 | Stops searching after the first match is found |
| cut -d: -f1 | Extracts only the line number from the "line number:content" format |
| Result | Retrieves line number 2, where "banana" first appears |
Explanation
grep -n outputs search results with line numbers, and combining with -m1 retrieves only the first matching line.
When only the line number is needed, use cut to extract it.
Getting the Line Number of the Last Match with grep
Create File
cat << 'EOF' > input.txt
apple
banana
orange
banana
grape
banana
EOF
Command
grep -n 'banana' input.txt | tail -n 1
Output
6:banana
Command
grep -n 'banana' input.txt | tail -n 1 | cut -d: -f1
Output
6
How It Works
| Item | Description |
|---|---|
| grep -n | Outputs matching lines in "line number:content" format |
| grep -n 'banana' input.txt | Retrieves all lines matching "banana" |
| tail -n 1 | Retrieves the last line of the matching results |
| cut -d: -f1 | Retrieves only the portion before the delimiter : (the line number) |
| Result | Retrieves line number 6, where "banana" last appears |
Explanation
Since grep alone cannot directly retrieve only the last matching line number, tail -n 1 is used in combination. Adding cut lets you retrieve only the line number without the line content.
Extracting Only Matching Line Numbers with awk from grep Output
Create File
cat << 'EOF' > input.txt
apple
banana
orange
banana
grape
banana
EOF
Command
grep -n 'banana' input.txt
Output
2:banana
4:banana
6:banana
Command
grep -n 'banana' input.txt | awk -F: '{print $1}'
Output
2
4
6
How It Works
| Command | Role |
|---|---|
| grep -n 'banana' input.txt | Outputs matching lines and their line numbers in "line number:content" format |
| awk -F: '{print $1}' | Uses : as the delimiter and extracts only the first column (line number) |
| grep -n 'banana' input.txt | awk -F: '{print $1}' | Retrieves only the line numbers of matching lines |
Explanation
Using grep's -n option assigns line numbers to matching lines.
Processing that output with awk makes it easy to extract only the matching line numbers.
Editing a Specific Line Using Line Numbers from grep Combined with sed
Create File
cat << 'EOF' > input.txt
apple
banana
orange
grape
melon
EOF
Command
grep -n '^orange$' input.txt
Output
3:orange
Command
sed -i '' '3s/orange/lemon/' input.txt
Command
cat input.txt
Output
apple
banana
lemon
grape
melon
How It Works
| Item | Description |
|---|---|
| grep -n | Displays each line with its line number prepended |
| ^orange$ | Searches for lines that exactly match "orange" |
| 3:orange | Indicates that "orange" exists on line 3 |
| sed '3s/orange/lemon/' | Replaces "orange" with "lemon" on line 3 |
| -i | Updates the file directly |
Explanation
Using grep -n lets you confirm the line number of a target string.
Passing the confirmed line number to sed allows you to safely edit only that specific line.
Tips for Speeding Up Line Number Searches in Large Files with grep
Create File
cat << 'EOF' > input.txt
INFO startup completed
INFO loading modules
ERROR database connection failed
INFO retrying connection
INFO retry successful
WARN disk usage 80%
INFO processing request
ERROR timeout detected
INFO processing request
INFO shutdown completed
EOF
Command
grep -n "ERROR" input.txt
Output
3:ERROR database connection failed
8:ERROR timeout detected
Command
LC_ALL=C grep -n "ERROR" input.txt
Output
3:ERROR database connection failed
8:ERROR timeout detected
Command
grep -n -m 1 "ERROR" input.txt
Output
3:ERROR database connection failed
How It Works
| Tip | Mechanism | Effect |
|---|---|---|
| -n | Displays line numbers alongside matching lines | Instantly confirms line numbers in grep searches |
| LC_ALL=C | Disables locale processing and searches byte by byte | Speeds up searching in large files |
| -m 1 | Stops searching after the specified number of matches | Faster when only the first match is needed |
| Use specific search strings | Reduces unnecessary match evaluations | Lowers CPU load |
| Target non-compressed files | Avoids decompression processing | Reduces I/O time |
Explanation
When performing line number searches in large files with grep, disabling locale processing via LC_ALL=C is one of the most effective ways to speed things up.
If only the first match is needed, combining the -m option avoids unnecessary scanning.
Key Points for Displaying Line Numbers with grep
The line number display feature in grep is a fundamental capability for quickly grasping the location of search targets.
It can be applied not only to single files but also to searches across multiple files or entire directories.
Furthermore, combining it with regular expressions, conditional searches, and tools like awk and sed enables more advanced text processing.
Mastering grep's line number feature will allow you to efficiently carry out log analysis and configuration file review tasks.

