By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
458,127 Members | 1,343 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 458,127 IT Pros & Developers. It's quick & easy.

Need to go back two lines one a match is found

P: n/a
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

Jul 19 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
In article <3f********@news.iprimus.com.au>, Andrew Rich
<vk****@hotmail.com> wrote:
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__
Jul 19 '05 #2

P: n/a
Andrew Rich <vk****@hotmail.com> wrote in message news:<3f********@news.iprimus.com.au>...
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.
Jul 19 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.