Grep lines before and after matched line

The command grep is really useful for finding matches of a certain word in files or streams. However, until recently I didn’t know how to display lines before and after the matched line(s).

Let’s say we have a file named test.txt that contains the following content:

ALICE was beginning to get
very tired of sitting by
her sister on the bank
and of having nothing to do:
once or twice she had peeped
into the book her sister was reading,
but it had no pictures or conversations in it,
"and what is the use of a book," thought Alice,
"without pictures or conversations?'

If we use grep to find lines matching “bank”, we write:

grep bank test.txt

and get:

her sister on the bank

If we want to list some line(s) before the matched line, we write:

grep -B1 bank test.txt

where the 1 denotes the number of lines to list, and get:

very tired of sitting by
her sister on the bank

If we want to list some line(s) after the matched line, we write:

grep -A2 bank test.txt

where the 2 denotes the number of lines to list, and get:

her sister on the bank
and of having nothing to do:
once or twice she had peeped

The two options can be combined as well, but I leave that as an exercise to the reader :-).

Advertisements
This entry was posted in programming and tagged . Bookmark the permalink.

One Response to Grep lines before and after matched line

  1. Fares says:

    This is what i was looking for. Thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s