Oh well, this question keeps popping up every few months.
How do I tail a large file with perl? Here is my crack at it, it uses
seek from the end of the file. Linux only for now. Bill Gates dosn't
seem to care about linux compatibility, so why should I care about
windows compatibility?
#!/usr/bin/perl -w
# Simple program to read the last n line(s) of a file.
# Reads from the end of the file for effeciency
# "\n" linux only,
# usage tailz filename numberoflines
use strict;
my $filename = shift or die "Usage: $0 file numlines\n";
my $numlines = shift;
my $byte;
# Open the file in read mode
open FILE, "<$filename" or die "Couldn't open $filename: $!";
# Rewind from the end of the file until count of eol 's
seek FILE,-1, 2; #get past last eol
my $count=0;
while (1){
seek FILE,-1,1;
read FILE,$byte,1;
if(ord($byte) == 10 ){$count++;if($count == $numlines){last}}
seek FILE,-1,1;
if (tell FILE == 0){last}
}
$/=undef;
my $tail = <FILE>;
print "$tail\n";
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.