Andrew Rich said:
Howdy,
I have a need to do this :-
1. find a match
2. go back three lines
3. read out lines 1 2 3
eg
apples
bannanas
oranges
match on oranges
back up three lines, output three lines
apples
bannanas
oranges
I infer that you are asking how to do this in perl. No?
If your file is not too big, you can read the whole thing into an
array, line by line. Then you can access any line:
__CODE__
#!/opt/perl/bin/perl
use strict;
my $infile = 'fruit.dat';
my @array_of_lines;
open(INPUT, $infile) or die "Unable to open $infile: $!\n";
@array_of_lines = <INPUT>;
close(INPUT);
for( my $i = 2; $i <= $#array_of_lines; $i++ ) {
if( $array_of_lines[$i] =~ /oranges/ ) {
print "match found at line $i:\n";
print $array_of_lines[$i-2];
print $array_of_lines[$i-1];
print $array_of_lines[$i];
}
}
__END__
If your file is too big, then you can read the file line-by-line and
keep the last two lines read in an array:
__CODE__
@array_of_lines = ();
open(INPUT, $infile) or die "Unable to open $infile: $!\n";
$array_of_lines[0] = <INPUT>;
$array_of_lines[1] = <INPUT>;
my $n = 2;
while(defined(my $line=<INPUT>)) {
$n++;
print "$n: $line";
if( $line =~ /oranges/ ) {
print "match found at line $n:\n";
print $array_of_lines[0];
print $array_of_lines[1];
print $line;
}
shift(@array_of_lines);
push(@array_of_lines,$line);
}
close(INPUT);
__END__