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 (my $line = <FH>) {
  if ($line =~ /Line 2/ .. $line =~ /Line 4/) { print $line; }
}

close(FH);

 

This will produce the following result.

Line 2
Line 3
Line 4

 

To print everything except Lines 2 through Line 4, use unless instead of if.

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

while (my $line = <FH>) {
  unless ($line =~ /Line 2/ .. $line =~ /Line 4/) { print $line; }
}

close(FH);

 

This will produce the following result.

Line 1
Line 5


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