Grep: show lines before and after the match in Linux

Want to help support this blog? Try out Oh Dear, the best all-in-one monitoring tool for your entire website, co-founded by me (the guy that wrote this blogpost). Start with a 10-day trial, no strings attached.

We offer uptime monitoring, SSL checks, broken links checking, performance & cronjob monitoring, branded status pages & so much more. Try us out today!

Profile image of Mattias Geniar

Mattias Geniar, January 02, 2016

Follow me on Twitter as @mattiasgeniar

You can add some additional parameters to your grep command, to search for keywords or phrases in files, to also show you the files that match before or after your match.

This is especially useful if the lines before or after that match are relevant for your search queries.

A normal grep looks like this.

$ grep 'keyword' /path/to/file.log

To also show you the lines before your matches, you can add -B to your grep.

$ grep -B 4 'keyword' /path/to/file.log

The -B 4 tells grep to also show the 4 lines before the match.

Alternatively, to show the log lines that match after the keyword, use the -A parameter.

$ grep -A 2 'keyword' /path/to/file.log

In this example, it will tell grep to also show the 2 lines after the match.

Because this will increase your output from a grep, you can also add the --color parameter (or to please US/UK folks, the --colour also works) to highlight your actual keywords.

A complete example, that shows the 5 lines before the match and 2 lines after the match, while highlighting the keyword(s), looks like this.

$ grep -B 5 -A 2 --color 'keyword' /path/to/file.log

And that’s it!



Want to subscribe to the cron.weekly newsletter?

I write a weekly-ish newsletter on Linux, open source & webdevelopment called cron.weekly.

It features the latest news, guides & tutorials and new open source projects. You can sign up via email below.

No spam. Just some good, practical Linux & open source content.