Perl file example - A program to extract lines from a file

After trying some other approaches, I finally create a Perl program to extract lines from the middle of a file. Just give it the line number to start at, and a second line number to stop at, and this Perl program will print all the lines from the file in that range.

The source code for this Perl program is shown below.

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 Perl file-oriented program, but very powerful. I guess that's the beauty of Perl, using Perl to work with files, and text processing.

 

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.