grep command to show lines after and before the keyword

In this post,I am sharing a useful option with linux grep command.In this tutorial, we will use grep command to show lines after and before the keyword . As a Linux System Engineer, sometimes I get the requirement to print lines above and below of a particular keyword in the file. Generally if you only use the command like grep keyword filename, it will print only the line which has the keyword.

Print Number of lines AFTER keyword matching lines

Option to use : -A

-A option will print the number of lines after keyword match in the lines.

Syntax

grep -A  keyword [path of filename]

Example : In this example, we are searching the keyword called linux. And the we will print 2 lines after keyword linux

sharad@LinuxMintBox /tmp $ grep -A 2 linux loremipsum.txt 
linux
Open Source
country
sharad@LinuxMintBox /tmp $

Print Number of lines BEFORE keyword matching lines

Option to use : -B

-B option will print the number of lines before keyword match in the lines.

Syntax

grep -B  keyword [path of filename]

example : In this example, we are searching the keyword called linux. And the we will print 2 lines before keyword linux

sharad@LinuxMintBox /tmp $ grep -B 4 linux loremipsum.txt 
green
white
orange
gray
linux
sharad@LinuxMintBox /tmp $ 

Print lines after and before of the keyword matching in the file

We can use both option -A and -B in same grep command .

Example.

sharad@LinuxMintBox /tmp $ grep -A 3 -B 4 linux loremipsum.txt 
green
white
orange
gray
linux
Open Source
country
People
sharad@LinuxMintBox /tmp $

Note: Many users also use grep with the pipe along cat command.
The below example will give more understanding.
Here, we are searching for linux keyword. Number of lines after keyword is 1 and before keyword is 5.I have used both options.
you can use either -A or -B as per your requirement.

sharad@LinuxMintBox /tmp $ cat loremipsum.txt |grep -A 1 -B 5 linux
blue
green
white
orange
gray
linux
Open Source
sharad@LinuxMintBox /tmp $ 

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.