Perl: How to extract lines from the middle of a text file

I’ve always been a big fan of the Unix head and tail commands, but there have been several times where I wanted to print a range of lines from the middle of a text file — not just the beginning or end of a file. Not liking the available solutions, I wrote my own solution in Perl.

Here’s the source code for a program named that prints lines from a text file beginning at the “start line” you specify and ending at the “stop line.”

The source code


if ($#ARGV < 2) {
    print "Usage: startLine stopLine filename\n";
    exit 1;

$start = $ARGV[0];
$stop  = $ARGV[1];
$file  = $ARGV[2];

open (FILE, $file) || die "Can't open file \"$file\".\n";

while (<FILE>) {
    if ($count >= $start  &&  $count <= $stop) {


How to run the program

If you have Perl installed already it should be simple to run this program. Just make this file executable, then type the name of this program, followed by (a) the first line it should print, (b) the last line it should print, and (c) the name of the file it should read. For example, if you want to print lines 300 through 500 of a 10,000 line file you would type this: 300 500 tenthousandlinefile.txt

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.