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.
Without any buildup, 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. Feel free to rename this program, and do with it as you
please, although I wouldn't mind if you leave the reference to devdaily.com at
the top of the file. :)
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
I guess one other piece of information might be useful -- how to run this
program!
If you have Perl installed already it should be a no-brainer. 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. So,
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.)
|