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 の配列を保持し、ファイルから読み取られるときに新しい行を 1 つシフトしながらプッシュします。改行は fgets によって返されるため、単純に implode を実行して、パディングされた配列を使用しても 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));

tailこれにより、 inからの出力が返さ$logれ、ログ ファイルに書き戻されます。

于 2010-02-11T22:18:15.743 に答える
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 に答える
0

最適なフォームは次のとおりです。

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