Grep Show Lines Before and After

Razvan Ludosanu
Razvan LudosanuFounder, learnbackend.dev
Published: November 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:

Bash
$ grep -C <number> <pattern> <file>

For example, to show 3 lines:

Bash
$ grep -C 3 "pattern" file.txt

Read our article on how to grep across multiple lines if you are trying to provide a multi-line grep input.

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

Bash
$ grep -B  <number>  <pattern>  <file>

For example, to show 3 lines:

Bash
$ grep -B 3 "pattern" file.txt

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:

Bash
$ grep -A <number> <pattern> <file>

For example, to show 3 lines:

Bash
$ grep -A 3 "pattern" file.txt

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:

Bash
$ grep -B 1 -A 2 "pattern" file.txt

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:

Bash
$ head -n $(( $(grep -m <number> -n <pattern> <file> | tail
-n 1 | cut -d ':' -f 1) - 1 )) <file>

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:

Bash
$ 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

The following command will attempt to display all the lines of the lorem.txt file before the one containing the second matched sed pattern.

Bash
$ head -n $(( $(grep -m 2 -n "sed" lorem.txt |
  tail -n 1 | cut -d ':' -f 1) - 1 )) lorem.txt

Which will output:

Bash
sed ut perspiciatis
unde omnis iste natus
ut labore et dolore

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.

Bash
head: illegal line count -- 0

Also note that, if the searched pattern doesn’t exist in the specified file, this command will output the following error message.

Bash
head: illegal line count -- -1

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:

Bash
$ tail -n $(( $(wc -l < < file> | tr -d ' ') - $(grep -m <number> -n <pattern> <file> |
  tail -n 1 | cut -d ':' -f 1)  )) <file>

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:

Bash
$ 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

The following command will attempt to display all the lines of the lorem.txt file after the one containing the second matched sed pattern.

Bash
$ tail -n $(( $(wc -l < lorem.txt | tr -d ' ') - $(grep -m 2 -n "sed" lorem.txt |
  tail -n 1 | cut -d ':' -f 1)  )) lorem.txt

Will output:

Bash
qui ratione voluptatem
neque porro quisquam
sed quia non numquam

Common pitfalls

Note that, if the searched pattern doesn’t exist in the specified file, this command will output the following error message.

Bash
-bash: 7 -   : syntax error: operand expected (error token is " ")
Written by
Razvan Ludosanu
Razvan LudosanuFounder, learnbackend.dev
Filed under

Related articles


Bash Comments

Comments will help make your scripts more readable

Reading User Input

Via command line arguments and prompting users for input

Curl Post Request

Use cURL to send data to a server

Upload Files With curl

Learn how to upload a file to FTP, SFTP servers, Artifactory, and AWS S3 using the curl command.

How To Copy A Directory In Linux

Learn how to copy directories and their content in Linux using the cp command with options like -r for recursive copying, -i for interactive mode, and -a for preserving attributes.

Create Groups In Linux

Learn how to manually and automatically create and list groups in Linux.

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.

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.

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.

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 Directories Recursively With mkdir

Learn how to recursively create nested directories using the mkdir command, Bash scripts, and Python scripts.

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.