1

我想从旧日志文件中删除所有行并保留底部的新 50 行。

我该怎么做这样的事情,如果可能的话,我们可以改变这些线条的方向,

normal input

111111
2222222
3333333
44444444
5555555

output like

555555
4444444
3333333
22222
111111

仅查看顶部和 50 或 100 行的新鲜日志。

如何加入这个?

// set source file name and path 
$source = "toi200686.txt"; 
// read raw text as array 
$raw = file($source) or die("Cannot read file"); 
// join remaining data into string 
$data = join('', $raw); 
// replace special characters with HTML entities 
// replace line breaks with <br />  
$html = nl2br(htmlspecialchars($data)); 

它将输出作为 HTML 文件。那么你的代码将如何运行呢?

4

5 回答 5

8
$lines = file('/path/to/file.log'); // reads the file into an array by line
$flipped = array_reverse($lines); // reverse the order of the array
$keep = array_slice($flipped,0, 50); // keep the first 50 elements of the array

从那里你可以用$keep. 例如,如果你想把它吐出来:

echo implode("\n", $keep);

或者

file_put_contents('/path/to/file.log', implode("\n", $keep));
于 2010-02-11T21:45:43.870 回答
3

这有点复杂,但使用的内存更少,因为整个文件没有加载到数组中。基本上,它保留一个长度为 N 的数组,并在从文件中读取新行时推入新行,同时将其移出。因为换行符是由 fgets 返回的,所以即使使用填充数组,您也可以简单地执行内爆来查看您的 N 行。

<?php
$handle = @fopen("/path/to/log.txt", "r");
$lines = array_fill(0, $n-1, '');

if ($handle) {
    while (!feof($handle)) {
        $buffer = fgets($handle);
        array_push($lines, $buffer);
        array_shift($lines);
    }
    fclose($handle);
}

print implode("",$lines);
?>

只是展示另一种做事的方式,尤其是在您没有tail可用的情况下。

于 2010-02-11T22:40:13.577 回答
1

这适用于截断日志文件:

exec("tail -n 50 /path/to/log.txt", $log);
file_put_contents('/path/to/log.txt', implode(PHP_EOL, $log));

这将返回tailin的输出$log并将其写回日志文件。

于 2010-02-11T22:18:15.743 回答
0

最佳形式是:

<?
print `tail -50 /path/to/file.log`;
?>
于 2010-02-11T22:24:24.340 回答
0

$tail此方法使用关联数组每次仅存储行数。它不会用所有行填充整个数组

$tail=50;
$handle = fopen("file", "r");
if ($handle) {
    $i=0;
    while (!feof($handle)) {
        $buffer = fgets($handle,2048);
        $i++;
        $array[$i % $tail]=$buffer;
    }
    fclose($handle);
    for($o=$i+1;$o<$i+$tail;$o++){
        print $array[$o%$tail];
    }
}
于 2010-03-07T08:05:12.293 回答