2010-02-11 46 views
0

我想從舊日誌文件中刪除所有行並保留最下面的50行。如何從日誌文件中保留最後n個行php

我怎樣才能做這樣的事情,如果可能,我們可以改變這些線的方向,

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文件。那麼你的代碼如何運行呢?

回答

7
$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)); 
+0

+1雖然當日志文件很大 – Gordon 2010-02-11 22:12:33

+0

非常感謝,但如何與這一個加入吧,他可能會遇到內存問題整個陣列? , //設置源文件名和路徑 $ source =「toi200686.txt」; //將原始文本讀取爲數組 $ raw = file($ source)或die(「Can not read file」); //將剩餘數據加入字符串 $ data = join('',$ raw); //用HTML實體替換特殊字符 //替換換行符與
$ HTML = nl2br(的htmlspecialchars($數據)); 它使輸出成爲html文件,所以你的代碼如何正確運行? 謝謝 – MIkeyy 2010-02-11 22:18:12

+1

我認爲最好在翻轉它之前獲取數組切片,以避免重複可能是一個大數組。 '$ keep = array_reverse(array_slice($ lines,count($ lines) - $ n-1,count($ lines)-1))'。 – 2010-02-11 22:21:41

1

這將工作截斷日誌文件:

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

這將返回從tail輸出$log並將其寫回日誌文件。

0

最優的形式是:

<? 
print `tail -50 /path/to/file.log`; 
?> 
+0

我建議你在* NIX平臺上,我的解決方案不能在Windowzzz上工作... – UncleMiF 2010-02-11 22:25:24

+0

確實會安裝Cygwin Tools。這種方法的問題是在回寫日誌 – Gordon 2010-02-11 22:28:40

3

這是一個比較複雜的,但使用較少的存儲器作爲整個文件沒有被加載到陣列中。基本上,它保持一個N長度的數組,並在從文件中讀取文件的同時按下新行,同時關閉一個文件。因爲換行符是由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

+0

+1時也會出現換行符。絕對不佔用資源......我只是在儘可能避免資源句柄的情況下:-) – prodigitalson 2010-02-11 22:44:07

+0

我現在感到困惑,告訴我我正在使用哪一種動作 – MIkeyy 2010-02-11 22:45:52

+0

@Mikeyy:取決於內存是否值得關注。最有可能的不是,考慮到這些是文本文件,所以任何解決方案都可以工作。 – 2010-02-11 22:50:04

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]; 
    } 
} 
相關問題