I’ve always been a big fan of the Unix head
and tail
commands, but there have been several times where I 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 solution in Perl.
Here’s the source code for a program named extract.pl that 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 startLine stopLine 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);
How to run the program
If you have Perl installed already it should be simple to run this program. Just make this file executable, then type the name of this program, followed by (a) the first line it should print, (b) the last line it should print, and (c) 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