如何最好地覆盖文件中的特定行? 我想要查找文件中的字符串“@parsethis”并用其他内容覆盖该行的其余部分。
如果文件非常大(如日志文件等),并且您愿意为内存消耗而牺牲速度,您可以打开两个文件,并使用文件而不是系统内存来执行Jeremy Ruten提出的技巧。
$source='in.txt';
$target='out.txt';
// copy operation
$sh=fopen($source, 'r');
$th=fopen($target, 'w');
while (!feof($sh)) {
$line=fgets($sh);
if (strpos($line, '@parsethis')!==false) {
$line='new line to be inserted' . PHP_EOL;
}
fwrite($th, $line);
}
fclose($sh);
fclose($th);
// delete old source file
unlink($source);
// rename target file to source file
rename($target, $source);
$command = "pathToShellScript folder1Name folder2Name myStyleVarName myStyleVarProp";
shell_exec($command);
/* shellScript */
#!/bin/bash
file=/var/www/vhosts/mydomain.com/$1/$2/scss/_variables.scss
str=$3"$4"
sed -i "s/^$3.*/$str;/" $file
或者如果你的文件不太大:
$sample = file_get_contents('sample');
$parsed =preg_replace('#@parsethis.*#', 'REPLACE TO END OF LINE', $sample);
你需要选择文件中不存在的分隔符“#”。
rename("./some_path/data.txt", "./some_path/data_backup.txt");
rename("./some_path/new_data.txt", "./some_path/data.txt");
所以在第一行中,您备份文件,在第二行中,您用新文件的内容替换文件。
据我所知,重命名返回一个布尔值。如果重命名成功,则为True,如果失败,则为false。因此,只有在第一步成功后才能运行第二步,以防止覆盖文件,除非已成功进行了备份。请查看:
https://www.php.net/manual/en/function.rename.php
希望对某些人有用。
祝好
Adrian
我可能会像Jeremy建议的那样去做,但这里还有另一种解决方案。这个方案没有经过测试或使用,适用于*nix系统。
$cmd = "grep '@parsethis' " . $filename;
$output = system($cmd, $result);
$lines = explode("\n", $result);
// Read the entire file as a string
// Do a str_repalce for each item in $lines with ""
file()
函数之后使用implode()
函数,那么您可能希望将file_put_contents()
函数用于同一行代码中以完成此操作。请注意,这不会更改原始意思。 - Frank N