Grep a line before or after a match in bash

Sometime when you grep a file on Linux you need to not only display the line where the result is found but also several lines before or after the match.

Grep as a useful function permitting you to do just that.

Let’s take an example file.

file.txt:

Title : login issue
Ticket number : 16417
Details : user password is no longer working.

Title : Broken keyboard
Ticket number : 16418
Details : the space key on the user keyboard no longer work

 

If the file is list of hundreds of this informations and you need to see only the information related to ticket 16417 you need to

cat file.txt|grep 16417

Will only return the result Ticket number : 16417  living out the useful informations

If you need to display a line after the grep match

cat file.txt| grep -A1 16417

will return :

Ticket number : 16417
Details : user password is no longer working.

But there is also useful information before  the match

You can associate the 2 options to display the line after and before

cat file.txt| grep -A1 -B1 16417

this will return all the information i need :

Title : login issue
Ticket number : 16417
Details : user password is no longer working.

Leave a Comment

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