Perl read file example - How to print a range of lines from a text file

Here's a Perl script that demonstrates how to do "something" for each line in a text file that falls between a given line number range, i.e., a starting line number and an ending line number.

In this Perl script all I do is print each line that falls between this "start" and "stop" range, but of course your own Perl program can do anything it needs to within this range. In short, this Perl script does the following:

  • Uses ARGV to verify the number of Perl command line arguments.
  • Uses the open function to open the text file.
  • Loops through each line in the text file, using the Perl filehandle named FILE.
  • Prints each line within the line number range we specified.

Here's my source code for this Perl program:


# purpose: print a range of lines from a text file.
# usage: first-line last-line input-file

# use ARGV to verify the number of perl command line arguments
@ARGV == 3 or die "Usage: first-line last-line input-file\n";
$first_line = $ARGV[0];
$last_line = $ARGV[1];
$filename = $ARGV[2];

# open the file (or die trying)
open(FILE, $filename) or die "Could not read from $filename, program halting.";

# loop through the file; start printing when you get to the first_line; exit the
# program when you get to last_line.
$count = 1;
while (<FILE>)
  # exit the program when you get to the last line
  if ($count > $last_line)
    close FILE;

  # print the current line if the line number is greater than our first param
  if ($count >= $first_line)
    print $_;

  # increment the line counter

# come here if last-line is greater than the number of lines in the file.
# print an error message here if you prefer.
close FILE;

Example usage

As you can see from the usage statement, you run this Perl script generically like this: first-line last-line input-file

As a specific example, if you want to use this Perl script to print lines 20 through 30 of a text file named text-file.txt, your command would look like this: 20 30 text-file.txt