A simple program to extract lines from a file

By Alvin J. Alexander, devdaily.com

The source code to a simple Perl program I created to extract line numbers from a file is shown below. Just specify the startLine, stopLine, and filename, and the program extracts the line numbers you specify.

Sample usage:

extract.pl 500 1000 myBigFile > smallerFile

Here's the code for extract.pl:

#!/usr/bin/perl

if ( $#ARGV < 2 )
{
  print "Usage: extract.pl firstLine lastLine 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);

As you can see, it's a simple program, but very powerful. I guess that's the beauty of Perl and text processing.


devdaily logo