A Perl extract program

Ever need a program to extract some lines from the middle of a file, say lines 50-500 of a 10,000 line file? Well, I did, so I wrote one in Perl. Here's the code for "extract.pl, which lets me extract lines from a file by specifying the firstLine and lastLine that I want printed from a file:

#!/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 (<FILE>)
{
  $count++;
  if ( $count >= $start  &&  $count <= $stop )
  {
    print;
  }
}

close(FILE);

 

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.