Link to home
Start Free TrialLog in
Avatar of morsa801tons
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!
Avatar of fim32
fim32

i suppose you could do this in a couple of different ways.  the easiest would probably be to grab the last line with last, and cut the value you want:

$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;
a=`tail -1 textfile`
echo $a
ASKER CERTIFIED SOLUTION
Avatar of bira
bira

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ozo
#if you have Perl 5.8
use Tie::File;
tie @array, 'Tie::File', "textfile" or die $!;
$date=substr($array[-1],0,15);