Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read n lines above the matched string in perl?

Tags:

scripting

perl

Say I have a file xx.txt and it contains the data

1 I am here

2 to work in 

3 Perl for writing

4 a script for 

5 myself

Suppose i want to search for string script and want to display the three lines above it , what should i do ?

like image 439
kanwarpal Avatar asked Feb 22 '23 10:02

kanwarpal


1 Answers

You can use an array as your print buffer.

my @array;
while (<DATA>) {
    push @array, $_;
    shift @array if @array > 4;
    print @array if /script/;
}


__DATA__
1 I am here
2 to work in 
3 Perl for writing
4 a script for 
5 myself

Various usage:

If you intend to use this as a stand-alone, you might consider using grep instead:

grep -B3 script xx.txt

Or perl one-liner if grep is not an option (e.g. you're on Windows):

perl -nwe 'push @a, $_; shift @a if @a > 4; print @a if /script/' xx.txt

If it is inside a script, you only need to supply your own file handle:

my @array;
open my $fh, '<', "xx.txt" or die $!

while (<$fh>) {
    push @array, $_;
    shift @array if @array > 4;
    print @array if /script/;
}
like image 112
TLP Avatar answered Mar 03 '23 22:03

TLP