Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to purge logs from a file

Status
Not open for further replies.

jawake

MIS
Jun 18, 2004
14
US
Hello,

I've written a simple script to capture web hits that match a certain criteria (e.g., referrer contains "google") and write those to a separate log file. That file grows pretty big and every now and then I want to purge it and keep only, say, the last 100 rows. I was going to do this with something like:

tail -100 logfile.txt > logfile.txt

But for some reason this just gives me an empty logfile.

Any thoughts on a clean way to do this in Perl?

Thanks
 
But for some reason this just gives me an empty logfile."

It's because > logfile.txt erases logfile.txt, so tail is operating on an empty file. Move or copy logfile to another file first, then do tail on that file, and it will work. E.g.,

mv logfile.txt logfile.bak
tail -100 logfile.bak > logfile.txt


You can then delete logfile.bak if you no longer want it around.
 
untested...
Code:
#!/usr/bin/perl -w
use strict;

open LOG, "<somefile" or die "can not open somefile, $!";
my @streamin = <LOG>;
close LOG or die "can not close somefile, $!";

my $streamsize = @streamin;

for ($i=0;$i=100;$i++)
{
   unshift (@streamout, @streamin[$streamsize-$i];
}

open RES, ">otherfile" or die "can not open otherfile, $!";
print RES @streamout;
close RES or die "can not close otherfile, $!";
 
Thanks a lot. I'll try these out.

Sorry for the slow response... I had checked the e-mail notification but didn't get anything... hmmmm.

Thanks again.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top