How to read n lines over a matching line in perl?

Say I have an xx.txt file and it contains data

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

Suppose I want to find a script line and want to display three lines above it, what should I do?

+4
source share
1 answer

You can use an array as a print buffer. A.

 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 uses:

If you intend to use this as standalone, you can use grep instead:

 grep -B3 script xx.txt 

Or perl one-liner if grep not a parameter (for example, you are 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 specify your own file descriptor:

 my @array; open my $fh, '<', "xx.txt" or die $! while (<$fh>) { push @array, $_; shift @array if @array > 4; print @array if /script/; } 
+8
source

Source: https://habr.com/ru/post/1397034/


All Articles