APLawrence.com -  Resources for Unix and Linux Systems, Bloggers and the self-employed


Note: modern "grep" has flags for printing lines before and after the match. Search for "context" in the man/info pages.

Basic usage is as simple as "grep pattern -A 3 -B 3 file", which will print 3 lines before and 3 lines after.

This is just a simple Perl/sed ( get Perl from Skunkware if you don't already have it) program that prints the text "around" a pattern. I call it "around", and you'd use it like this:

# around tony /etc/passwd
audit:x:79:17:Audit administrator:/tcb/files/audit:
ftp:x:20:50:anonymous ftp account:/usr/internet/ip/

As you can see, it prints the 4 lines before and the 4 lines after "tony". If you understand regex patterns, you can also use it that way. As presented here, this only searches one file; it wouldn't be very hard to change this to read from any number of files listed on the command line, but it would be more complicated, and I wanted to leave this very easy to understand for non-programmers. It could also easily take an argument that would specify how many lines to show before and after; again, I left that out to keep it simple.

I think it's written simply enough that anyone should be able to modify it if they need it to print more or less. Note that the very first line must point at wherever your Perl binary lives.

This isn't particularly fast, efficient or elegant. If you understand that by looking at it, then you are surely capable of writing a better version yourself, and wouldn't need this. This is for people who don't write their own programs or are just starting to: it's intended to be easy to understand, not great programming.

Non-programmers should note that using patterns that match more than one line can easily produce duplicate lines of output. For example, "around 'tony|kate' /etc/passwd" will list lines before and after "kate", and then the lines before and after "tony". That could be confusing if you aren't expecting it.

open(FILE,$file) or die "Can't open $file";
while (<FILE>) {
        if (/$search/o) {
                $start= $line -4;
                $start=1 if $start < 1;
                $end = $line +4;
                $cmd="/bin/sed -n $start,${end}p $file";
                print qx/$cmd/;

Got something to add? Send me email.

Increase ad revenue 50-250% with Ezoic

More Articles by

Find me on Google+

© Tony Lawrence

Kerio Samepage

Have you tried Searching this site?

Support Rates

This is a Unix/Linux resource website. It contains technical articles about Unix, Linux and general computing related subjects, opinion, news, help files, how-to's, tutorials and more.

Contact us

The history of the world teaches us that succession is dangerous and that the strong take what they want. It's not likely to be any different with Linux. (Tony Lawrence)

This post tagged: