tags:

views:

251

answers:

2

I am trying to get the last line of a file. The file, ff.log, is getting new data every second while ffmpeg is working. The log file looks like this:

frame= 20 fps= 0 q=7.7 size= 40kB time=1.24 bitrate= 266.1kbits/s
frame= 30 fps= 28 q=6.6 size= 51kB time=1.90 bitrate= 218.4kbits/s
frame= 40 fps= 24 q=6.6 size= 61kB time=2.60 bitrate= 191.4kbits/s
frame= 47 fps= 20 q=6.8 size= 65kB time=3.08 bitrate= 173.8kbits/s
frame= 64 fps= 22 q=7.0 size= 84kB time=4.20 bitrate= 163.8kbits/s
(keeps adding new lines every second or faster)

I have tried

$line = `tail -n 1 $file`;

I tried using fseek() with a "php tail script" .

Both resulted in some strange behaviour.

I ran the my script from command line and it outputted:

frame= XX fps= XX q=XX size= XX time=XX bitrate= XXkbits/s

Where XX kept increasing for several seconds until it was the value from the last line.

Now, In my php script, I have

echo "--$last_line--";

When I run it, the output is for several seconds, just the log line with increasing numbers. When when it reaches the end, the output is

--ame= 7119 fps= 9 q=13.8 size= 4809kB time=474.50 bitrate= 83.0kbits/s

Note that the first "--" collided with the $last_line and the other "--" is not there.

What is the explanation for this strange behavior?


UPDATE: See what's actually happening

Here is a Flash demo

teste.php.txt -- Source

ff.log -- the log file

+3  A: 

This is probably because it's thinking you're asking it to print "$lastline--" ...

Try

echo '--' . $lastline . '--';

you might also want to do something like

var_dump($lastline); die();

To show you exactly what is in the variable, as this will give you more information.

However, I suggest you post your whole script, so someone can try and see what the issue is.

EDIT Looking at the file, it seems it's using ONLY \r as a line terminator. This causes the problems you see (it means "return to the start of the line") - this means that all of the log is showing as the last line.

Try using he command

cat ff.log | tr "\r" "\n" | tail -n 2 | head -n 1

to get the last line of the log.

Mez
That did not work. As you suggested I added var_dump but it also does the same thing. See the video screenshot I added.
Alex L
Thanks a lot, the new command worked perfectly. I didn't think \r cold cause that. Learning something new.
Alex L
A: 

Both the tail command and the PHP script have the same problem. They seek to the end of the file, back up to the previous end-of-line, then read and print everything from there to the end of the file.

That's fine if the file is not growing very quickly. When the file grows quickly you get multiple lines returned.

Try either of these:

$line = `tail -n 1 $file | tail -n 1`;
$line = `tail -n 1 $file | head`;

The first is slightly more accurate, but the second is faster.

Devon_C_Miller
Thanks but that did not help. I will try to make screenshots.
Alex L