Grep Show Lines Before and After
Razvan Ludosanu
Founder, learnbackend.dev
Published: 11/30/2023
The short answer
To show N lines before and after the grep results, including the lines containing the matched search pattern, you can use the -C flag (short for context) as follows:
$ grep -C <number> <pattern> <file>
Run in Warp
For example, to show 3 lines:
$ grep -C 3 "pattern" file.txt
Run in Warp
Read our article on how to grep across multiple lines if you are trying to provide a multi-line grep input.
Easily retrieve this command using Warp’s AI Command Search
If you’re using Warp as your terminal, you can easily retrieve this command using the Warp AI Command Search feature:
Entering grep show context lines in the AI Command Search will prompt a grep command that can then quickly be inserted into your shell by doing CMD+ENTER.
Showing N lines before the grep result
$ grep -B <number> <pattern> <file>
Run in Warp
For example, to show 3 lines:
$ grep -B 3 "pattern" file.txt
Run in Warp
Showing N lines after thegrep result
To show N lines after the grep results, including the lines containing the matched search pattern, you can use the -A flag (short for after) as follows:
$ grep -A <number> <pattern> <file>
Run in Warp
For example, to show 3 lines:
$ grep -A 3 "pattern" file.txt
Run in Warp
Selectively showing N lines before and after the grep result
To selectively show N lines before and M lines after the grep results, including the matched search pattern, you can use a combination of the aforementioned -B and -A flags.
For example, to show 1 line before and 2 lines after:
$ grep -B 1 -A 2 "pattern" file.txt
Run in Warp
Showing all lines before the grep result
To show all lines before the grep results, not including the search pattern, you can use a combination of the following commands:
$ head -n $(( $(grep -m <number> -n <pattern> <file> | tail
-n 1 | cut -d ':' -f 1) - 1 )) <file>
Run in Warp
Where:
- head -n displays the first N lines of a file.
- grep -m <number> -n <pattern> <file> searches for the pattern in the file and returns the line number and corresponding lines where the pattern is found. The -m option flag tells grep to stop after finding number matches—leave it out if you want to find all matches.
- tail -n 1 displays the last line of the matches returned by grep
- cut -d ':' -f 1 returns the line number of the pattern matched by grep.
- $( … ) is used to substitute a command by the result of its execution.
- $(( … )) is an expansion used to perform arithmetic calculations.
For example, considering the following file:
$ cat lorem.txt
sed ut perspiciatis
unde omnis iste natus
ut labore et dolore
sed quia consequuntur
qui ratione voluptatem
neque porro quisquam
sed quia non numquam
Run in Warp
The following command will attempt to display all the lines of the lorem.txt file before the one containing the second matched sed pattern.
$ head -n $(( $(grep -m 2 -n "sed" lorem.txt |
tail -n 1 | cut -d ':' -f 1) - 1 )) lorem.txt
Run in Warp
Which will output:
sed ut perspiciatis
unde omnis iste natus
ut labore et dolore
Run in Warp
Common pitfalls
Note that when using the -m 1 flag, if the pattern matched by grep is present in the first line of the file, this command will output the following error indicating that the head command cannot print the first 0 lines of the specified file.
head: illegal line count -- 0
Run in Warp
Also note that, if the searched pattern doesn’t exist in the specified file, this command will output the following error message.
head: illegal line count -- -1
Run in Warp
Showing all lines after the grep result
To show all lines after the grep result, not including the search pattern, you can use a combination of the following commands:
$ tail -n $(( $(wc -l < < file> | tr -d ' ') - $(grep -m <number> -n <pattern> <file> |
tail -n 1 | cut -d ':' -f 1) )) <file>
Run in Warp
Where:
- tail -n displays the last N lines of a file.
- wc -l returns the number of lines of the specified file.
- tr -d ' ' removes space characters from the string returned by wc.
- cut -d ':' -f 1 returns the line number of the pattern matched by grep.
- $( … ) is used to substitute a command by the result of its execution.
- $(( … )) is an expansion used to perform arithmetic calculations.
For example, considering the following file:
$ cat lorem.txt
sed ut perspiciatis
unde omnis iste natus
ut labore et dolore
sed quia consequuntur
qui ratione voluptatem
neque porro quisquam
sed quia non numquam
Run in Warp
The following command will attempt to display all the lines of the lorem.txt file after the one containing the second matched sed pattern.
$ tail -n $(( $(wc -l < lorem.txt | tr -d ' ') - $(grep -m 2 -n "sed" lorem.txt |
tail -n 1 | cut -d ':' -f 1) )) lorem.txt
Run in Warp
Will output:
qui ratione voluptatem
neque porro quisquam
sed quia non numquam
Run in Warp
Common pitfalls
Note that, if the searched pattern doesn’t exist in the specified file, this command will output the following error message.
-bash: 7 - : syntax error: operand expected (error token is " ")
Run in Warp
Written by
Razvan Ludosanu
Founder, learnbackend.dev
Filed Under
Related Articles
List Open Ports in Linux
Learn how to output the list of open TCP and UDP ports in Linux, as well as their IP addresses and ports using the netstat command.
Count Files in Linux
Learn how to count files and folders contained in directories and subdirectories in Linux using the ls, find, and wc commands.
How to Check the Size of Folders in Linux
Learn how to output the size of directories and subdirectories in a human-readable format in Linux and macOS using the du command.
Linux Chmod Command
Understand how to use chmod to change the permissions of files and directories. See examples with various chmod options.
POST JSON Data With Curl
How to send valid HTTP POST requests with JSON data payloads using the curl command and how to avoid common syntax pitfalls. Also, how to solve the HTTP 405 error code.
Format Command Output In Linux
Learn how to filter and format the content of files and the output of commands in Linux using the awk command.
Create Groups In Linux
Learn how to manually and automatically create and list groups in Linux.
Switch Users In Linux
Learn how to switch between users, log in as another user, and execute commands as another user in Linux.
Remover Users in Linux
Learn how to remove local and remote user accounts and associated groups and files in Linux using the userdel and deluser commands.
Delete Files In Linux
Learn how to selectively delete files in Linux based on patterns and properties using the rm command.
Find Files In Linux
Learn how to find and filter files in Linux by owner, size, date, type and content using the find command.
Copy Files In Linux
Learn how to safely and recursively copy one or more files locally and remotely in Linux using the cp and scp command.