How to print the corresponding line and the following three lines in Perl?

I need to find a template and write this line, as well as the next 3 lines to a file (FILE). Is this the right way to do this? Thanks.

print FILE if /^abc/;
$n=3 if /^abc/;
print FILE if ($n-- > 0);
+3
source share
6 answers

I like the operator ..:

perl -ne 'print if (/abc/ and $n=3) .. not $n--'

but you did not describe what should happen if the abc pattern is repeated in the next three lines. If you want to restart the counter, your approach is correct if you fix a small mistake with double printing.

perl -ne'$n=4 if/abc/;print if$n-->0'
+5
source

You can simplify its use of the flags variable to find out whether to print a string:

while( <$input> ) {
    $n=4 if /^abc/; 
    print FILE if ($n-- > 0);
    }

Besides simplification, it also fixes the problem: in your version, the string abc will be printed twice.

+5

grep (1). :

grep abc --after-context=3

"-" , . Perl.:)

, , , . grep (1) reset . ​​

+5

:

#!/usr/bin/perl
use strict;
use warnings;

while ( my $line = <DATA> ) {
    if ( $line =~ /^abc/ ) {
        print $line;
        print scalar <DATA> for 1 .. 3;
    }
}
__DATA__
x
y
z
abc
1
2
3
4
5
6
+2

...

#!/usr/bin/perl

use strict;

my $count = 0;
while (<DATA>) {
    $count = 1 if /abc/;
    if ($count >= 1 and $count <= 3) {
        next if /abc/;
        print;
        $count++;
    }
}

__DATA__
test
alpha
abc
1
234123
new_Data
test
0

. - :

my $count = 0;
while ( my $line = pop @file ) {
   if ( /^abc/ ) {
      $count = 4;
   }

   if ( $count > 0 ) {
       print FILE $line;
       $count--;
   }
}

:

  • , .
  • printing newlines or not, of course, is optional, as well as inserting a file. Different people have different styles, this is one of the things that people love about Perl!
-3
source

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


All Articles