Perl file example - extract lines from the middle of a file

A Perl program to extract lines from the middle of a file

I've always been a big fan of the Unix head and tail commands, but several times I have 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.

Here is the source code for a program named "extract.pl", which prints lines from a text file beginning at the start line you specify and ending at the stop line.

The extract.pl source code

#!/usr/bin/perl

if ( $#ARGV < 2 )
{
  print "Usage: extract.pl start stop filename\n";
  exit 1;
}

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

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

$count=0;
while ()
{
$count++;
if ( $count >= $start && $count <= $stop )
{
print;
}
}

close(FILE);

How to run the program

If you have Perl installed already it should be simple to run this program. Just type the name of this program, followed by the first line it should print, then the last line it should print, and finally 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:

locate.pl 300 500 tenthousandlinefile.txt

Bummer, I found a major bug in this program after posting it. The while statement above is wrong, and therefore this program will not work as shown. The while line needs to read as follows for the program to work properly:

while (<FILE>)

A small change, but that's an important one. (I try to release service packs as quick as I can.)

 

Post new comment

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