FreeKB - Get a range of lines from a file in Perl
Get a range of lines from a file in Perl

Home > Search


Print a range of lines in a file

Let's say file.txt contain the following text.

Line 1
Line 2
Line 3
Line 4
Line 5

 

To print text between Line 2 and Line 4.

my $file = "/path/to/file.txt";
open(FH, '<', "$file") or die "cannot open $file $! \n";

while (<FH>) {
  if ($_ =~ /Line 2/../Line 4/) {
    print $_;
  }
}

close(FH);

 

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments