Get the current line and next 5 lines

L

Larry Doan

In a shell script or Perl, how do I open a file, find what I'm looking then

Case 1: grab that line + the next 2 lines
Case 2: grab that line + the previous 2 lines?

TIA,
Larry
 
A

Andrew Shitov

In a shell script or Perl, how do I open a file, find what I'm looking then
Case 1: grab that line + the next 2 lines
Case 2: grab that line + the previous 2 lines?


1.

open FILE, "d:/1.html";
while (<FILE>){
last if /$pattern/;
}
my ($curr, $next1, $next2) = <FILE>;
close FILE;

print "$curr$next1$next2";

2.

my ($prev1, $prev2);
open FILE, "filename.txt";
while (<FILE>){
last if /$pattern/;
$prev2 = $prev1;
$prev1 = $_;
}
close FILE;
my $curr = $_;

print "$prev2$prev1$curr";
 
G

Gunnar Hjalmarsson

Larry said:
In a shell script or Perl, how do I open a file, find what I'm
looking then

Case 1: grab that line + the next 2 lines
Case 2: grab that line + the previous 2 lines?

Let's see the code you have so far.
 
B

Bill Marcum

In a shell script or Perl, how do I open a file, find what I'm looking then

Case 1: grab that line + the next 2 lines
Case 2: grab that line + the previous 2 lines?
If you have Gnu grep, look at the -A and -B options.
 
N

nobull

In a shell script or Perl, how do I open a file, find what I'm looking then

Case 1: grab that line + the next 2 lines
Case 2: grab that line + the previous 2 lines?

In Perl I'd use a rolling buffer to get previous lines.

my @buffer;
$#buffer = 2; # 3 line buffer (or whatever)
while (<>) {
push @buffer, $_;
shift @buffer;
next unless defined $buffer[0]; # No-op until buffer full
print @buffer if found_what_I_am_looking_for($_);
}

To get next lines you can either use the above approach (but test the
condition on $buffer[0]) or simply use a counter:

my $counter = 0;
while(<>) {
$counter = 3 if found_what_I_am_looking_for($_);
print if $counter-- > 0;
}

The newsgroup comp.lang.perl does not exist (see FAQ). Please do not
start threads here.
 
W

William Park

In said:
In a shell script or Perl, how do I open a file, find what I'm looking then

Case 1: grab that line + the next 2 lines
Case 2: grab that line + the previous 2 lines?

man grep (-A -B)
 

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,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top