morsa801tons
asked on
Perl, Reading last line from a file
Hi!
i got a text file with multiple lines, and want to save a field from the last line of this file into a variable... how i can do it?
Apr 30 13:48:46 mobydic pop3d: LOGIN, user=z100332-m429, ip=[::ffff:80.33.236.71]
Apr 30 13:48:47 mobydic pop3d: LOGOUT, user=z100332-m429, ip=[::ffff:80.33.236.71], top=0, retr=0
Apr 30 13:51:00 mobydic pop3d: LOGIN, user=z100332-m429, ip=[::ffff:80.33.236.71]
Apr 30 13:51:00 mobydic pop3d: LOGOUT, user=z100332-m429, ip=[::ffff:80.33.236.71], top=0, retr=0
Apr 30 13:54:02 mobydic pop3d: LOGIN, user=z100332-m429, ip=[::ffff:80.33.236.71]
Apr 30 13:54:02 mobydic pop3d: LOGOUT, user=z100332-m429, ip=[::ffff:80.33.236.71], top=0, retr=0
Apr 30 13:54:59 mobydic pop3d: LOGIN, user=z100332-m429, ip=[::ffff:80.33.236.71]
Apr 30 13:54:59 mobydic pop3d: LOGOUT, user=z100332-m429, ip=[::ffff:80.33.236.71], top=0, retr=0
Want to save into $date ---> Apr 30 13:54:59
Thanks in advance!
i got a text file with multiple lines, and want to save a field from the last line of this file into a variable... how i can do it?
Apr 30 13:48:46 mobydic pop3d: LOGIN, user=z100332-m429, ip=[::ffff:80.33.236.71]
Apr 30 13:48:47 mobydic pop3d: LOGOUT, user=z100332-m429, ip=[::ffff:80.33.236.71], top=0, retr=0
Apr 30 13:51:00 mobydic pop3d: LOGIN, user=z100332-m429, ip=[::ffff:80.33.236.71]
Apr 30 13:51:00 mobydic pop3d: LOGOUT, user=z100332-m429, ip=[::ffff:80.33.236.71], top=0, retr=0
Apr 30 13:54:02 mobydic pop3d: LOGIN, user=z100332-m429, ip=[::ffff:80.33.236.71]
Apr 30 13:54:02 mobydic pop3d: LOGOUT, user=z100332-m429, ip=[::ffff:80.33.236.71], top=0, retr=0
Apr 30 13:54:59 mobydic pop3d: LOGIN, user=z100332-m429, ip=[::ffff:80.33.236.71]
Apr 30 13:54:59 mobydic pop3d: LOGOUT, user=z100332-m429, ip=[::ffff:80.33.236.71], top=0, retr=0
Want to save into $date ---> Apr 30 13:54:59
Thanks in advance!
a=`tail -1 textfile`
echo $a
echo $a
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
#if you have Perl 5.8
use Tie::File;
tie @array, 'Tie::File', "textfile" or die $!;
$date=substr($array[-1],0, 15);
use Tie::File;
tie @array, 'Tie::File', "textfile" or die $!;
$date=substr($array[-1],0,
$line = `last -1 textfile`;
$line =~ /(.{15})/;
$date = $1;
if you don't have last, or want to do an all-perl solution... well, depending on how long this text file is, you could just suck and throw away every line:
open FH,"textfile";
while (! eof(FH)) { $line=<FH>; }
$line=~/(.{15});
$date=$1;