in reply to searching for a keyword with context window

If your file contains paragraphs (ie. blank lines between reasonable sized block of text, something like this might work. It is pretty quick, processing a 587 MB test file below (replicated several dozen times to get a file of comparable size) in under a minute.

You can adjust the definition of a 'word' to suit. I've specified 1 to 5 words either side to account for the word being at the start or end of a paragraph.

#! perl -sw use strict; our $WORDS ||= 1; our $KEYWORD || die "-KEYWORD=word needed"; local $/ = ''; # Paragraph mode my $re_word = qr[\S+\s+]; my $re_5w_key_5w = qr[ ( $re_word {1,$WORDS} \Q($KEYWORD\E[,.;:!?]*\s+ $re_word {1,$WORDS} ) ]ix; open IN, '<', $ARGV[ 0 ] or die $!; while( <IN> ){ if( $_ =~ $KEYWORD ) { while( $_ =~ m[$re_5w_key_5w]g ) { print "'$1'\n---\n"; } } }

Results:

[ 0:58:39.10] P:\test>404751 -WORDS=1 -KEYWORD=poverty "Rhetoric - Ari +stotle.txt" 'or poverty; it ' --- 'or poverty but ' --- 'or poverty, of ' --- 'or poverty or ' --- 'his poverty, a ' --- 'in poverty or ' --- [ 0:58:50.09] P:\test>404751 -WORDS=3 -KEYWORD=poverty "Rhetoric - Ari +stotle.txt" 'to wealth or poverty; it is of ' --- 'to wealth or poverty but to appetite. ' --- 'of wealth or poverty, of being lucky ' --- 'by sickness or poverty or love or ' --- 'disregard of his poverty, a man aging ' --- 'by us in poverty or in banishment, ' --- [ 0:58:53.10] P:\test>404751 -WORDS=5 -KEYWORD=poverty "Rhetoric - Ari +stotle.txt" 'action due to wealth or poverty; it is of course true ' --- 'due not to wealth or poverty but to appetite. Similarly, with ' --- 'the sense of wealth or poverty, of being lucky or unlucky. ' --- 'are afflicted by sickness or poverty or love or thirst or ' --- 'man by disregard of his poverty, a man aging war by ' --- 'who stand by us in poverty or in banishment, even if ' ---

Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"Think for yourself!" - Abigail
"Memory, processor, disk in that order on the hardware side. Algorithm, algorithm, algorithm on the code side." - tachyon