【问题标题】:Fastest way to search and remove/add line from/to file从文件中搜索和删除/添加行的最快方法
【发布时间】:2012-10-10 22:47:48
【问题描述】:
我想知道从潜在的大文件中删除特定行(如果存在)的最快方法是什么。
所以例如我想要以下行
abc
从文件中删除
yxz
srtabc
abc
efg
成为
yxz
srtabc
efg
另外,如果文件不存在,我想在文件中添加一行。
文件的顺序无关紧要,如果它可以提高搜索性能,则可以对其进行排序。
性能从来都不是我的强项,所以我在确定最佳路径时遇到了一些麻烦。
【问题讨论】:
标签:
php
performance
sorting
file-io
file-search
【解决方案1】:
为了性能,不要使用php。
但是,如果您坚持,并且您只需要一次替换操作,请读入整个文件,然后替换该行(作为字符串),然后将其写回。 IE。不要将文件分成单独的行,这会使事情变得比必要的慢。
这应该是诀窍:
$input = file_get_contents($filename_in);
$find = "abc..";
$find_q = preg_quote($find,'/');
$output = preg_replace("/^$find_q(\n|\$)/m","",$input);
file_put_contents($filename_out,$output);
它会删除恰好包含$find 的行,包括尾随的换行符。如果最后一行不是\n 终止,它仍然会被删除。
要测试一条线是否存在,请采用类似的方法:
$find_q = preg_quote($find,'/');
if ( !preg_match("/^$find_q(\n|\$)/m",$input) )
{
$input .= $find."\n"; // note: this assumes that $input is \n terminated
}
【解决方案2】:
我不建议使用file_put_contents 或file_get_contents,因为它会一次将文件的所有内容加载到 PHP 中,如果您使用的是大文件,这对您不起作用。
您可以使用 2 个文件 .. 并在另一个文件之后读取它们 ..... 替换您需要替换的任何内容,然后在最后重命名 .... 这仅在处理非常大的文件时才有效
概念教授
set_time_limit(0);
$baseFile = "log.txt";
$tempFile = $baseFile . ".temp";
touch($tempFile);
$findAndReplace = array("abc" => "","efg"=>"WWW");
$fileTemp = fopen($tempFile, "a+");
$fileBase = fopen($baseFile,"r");
while ( !feof($fileBase)) {
$var = trim(fgets($fileBase));
if (array_key_exists($var, $findAndReplace)) {
var_dump($var);
$var = $findAndReplace[$var];
}
if (!empty($var))
fwrite($fileTemp , $var . PHP_EOL);
}
fclose($fileBase);
fclose($fileTemp);
unlink($baseFile);
rename($tempFile, $baseFile);