On Tue, 7 Jan 2003 04:23:22 -0800 (PST), [EMAIL PROTECTED]
(Admin-Stress) wrote:

>Hi,
>
>Anyone have the fastest and efficien way to tail a text file ?
>
>suppose I have a text file "example.txt" and I want to print the last X lines.
>

Well there are alot of "ifs" to consider. How big the file is will
determine if you want to use a method which loads each line into an
array, usually you want to avoid that.

I'm guessing that the fastest and most efficient method is to
grab a "chunk" off the end of the file, then read that. But this assumes
you have some sort of average line length to use to compute the
"chunk size". 
########################################################
#!/usr/bin/perl -w
# usage tailz  filename  
use strict;

my $filename = shift or die "Usage: $0 file \n";
# Open the file in read mode
open FILE, "<$filename" or die "Couldn't open $filename: $!";

# Rewind from the end of the file 
seek FILE,0, 2;  #go to EOF
seek FILE,-2048,2; #get last 2k bytes

$/=undef;
my $tail = <FILE>;
print "$tail\n";
exit;
############################################################

If you absolutely need "x" number of lines instead of "x" number of
bytes, you can modify the above to load the chunk into an array and
print the last x lines of the array.  Some people have tried to count
the number of "\n" characters back from the end of the file, but I bet
just putting the chunk in an array is faster.

Here is a method which will give you the last "x" lines, but the catch
is you must assume an average line length to compute how big a chunk
to grab off.
#######################################################
#!/usr/bin/perl -w
# example for files with max line lengths < 400, but it's adjustable
# usage tailz  filename  numberoflines
use strict;

die "Usage: $0 file numlines\n" unless @ARGV == 2;
my ($filename, $numlines) = @ARGV;

my $chunk = 400 * $numlines; #assume a <= 400 char line(generous)
                                
# Open the file in read mode
open FILE, "<$filename" or die "Couldn't open $filename: $!";
my $filesize = -s FILE;
if($chunk >= $filesize){$chunk = $filesize}
seek FILE,-$chunk,2; #get last chunk of bytes

my @tail = <FILE>;
if($numlines >= $#tail +1){$numlines = $#tail +1}
splice @tail, 0, @tail - $numlines;

print "@tail\n";
exit;
##########################################################























-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to