Finding text and what surrounds it - contextual grep
Archive - Originally posted on "The Horse's Mouth" - 2009-10-30 10:04:43 - Graham Ellisgrep is a very useful tool for finding all the lines in a file (or series of files) that contain a particular string or match some other pattern / criteria. For example, I have a file that contains data for 52 staff members and I want to find who knows Lua ...
[trainee@melksham Download]$ grep Lua requests.xyz
lisa PHP Python Lua ASP Perl Java
graham Lua Perl Tcl/Tk
[trainee@melksham Download]$
But what if I want to see the context of my matches - to be given back not only the matched lines, but a few lines before and after the match to see what it relates too - "other nearby employees" in my example, but more commonly "the rest of the paragraph / example" in the case of text files. On Linux's grep, you can use the -A and -B options to specify the number of lines to display before and after each match, and the -C option if you want to show the same number before and after. Let's see that:
[trainee@melksham Download]$ grep -A2 -B1 Lua requests.xyz
kerry Perl Tcl/Tk Ruby MySQL
lisa PHP Python Lua ASP Perl Java
margaret XML Perl Ruby MySQL Tcl/Tk
nina Tcl/Tk Perl ASP Ruby
--
fred MySQL Perl Java XML
graham Lua Perl Tcl/Tk
harry PHP Python Java
ivan Ruby Java Perl Tcl/Tk MySQL
[trainee@melksham Download]$ grep -C3 Lua requests.xyz
iris Perl MySQL Java Tcl/Tk
jenny XML Perl Ruby ASP
kerry Perl Tcl/Tk Ruby MySQL
lisa PHP Python Lua ASP Perl Java
margaret XML Perl Ruby MySQL Tcl/Tk
nina Tcl/Tk Perl ASP Ruby
olivia MySQL Python ASP PHP
--
david Perl Tcl/Tk Java
ed Ruby Perl Java PHP
fred MySQL Perl Java XML
graham Lua Perl Tcl/Tk
harry PHP Python Java
ivan Ruby Java Perl Tcl/Tk MySQL
john PHP XML Java Perl
[trainee@melksham Download]$
If you're on a system that's got a version of grep that doesn't support these options, what can you do? Well - you could do worse that write a Perl script - in fact we've used the requirement for a contextual grep for an example on our Perl Programming course.