Need to go back two lines one a match is found

A

Andrew Rich

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
 
J

Jim Gibson

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__
 
N

nobull

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

# Untested!

my @buffer;
$#buffer = 2;
while (<>) {
push @buffer => $_;
shift @buffer;
print @buffer if /oranges/;
}

This newsgroup does not exist (see FAQ). Please do not start threads here.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top