我正在尝试制作一个脚本,以使用流读取和写入特定的行,而无需实际打开和写入整个文件。
例如:文本文件大 1gb,包含 1000 多行。格式是.. IPv4/IPv6=当前时间
我当前的脚本可以很好地阅读,但是我在特定的行上编写时遇到了问题,而不必使用打开整个文件并花费大量时间的数组中的文件放置内容。
这是我的代码:
<?php
// Del First Char
function trimit( $string ) {
return substr( $string, 1 );
}
// Ini the line count
$linecount = 0;
// Open File by Line
$handle = fopen("users.txt", "r+");
if ($handle) {
// Read line
while (($line = fgets($handle)) !== false) {
// Trim line to time
$alt = strstr($line, '=');
$alt = trimit($alt);
// IF line is older than 10 minutes, clear it
if (time()-600 > $alt)
{
$newcount = 0;
$fp = fopen("users.txt", "w+");
while (($line2 = fgets($fp)) !== false) {
if ($newcount === $linecount) {
fwrite($fp, $line2);
echo "worked";
}
$newcount++;
}
fclose($fp);
}
$linecount++;
}
fclose($handle);
} else {
echo "FATAL ERROR: Could not read file";
}
?>
我遇到的问题:使用 int 重写整个文件,而不是在匹配的搜索行后重写特定行
请任何帮助或澄清真的会有所帮助<3
我会使用shell_exec()
,因为操作系统索引文件,并且您的搜索/替换方法的开销很小,您可能永远不会看到影响。
实际的linux
命令是:
find /var/www/directory/file.txt -type f -readable -writable -exec sed -i "s/string_you_are_looking_for/replacement_text/g" {} ;
添加到shell_exec()
:
shell_exec('find /var/www/directory/file.txt -type f -readable -writable -exec sed -i "s/string_you_are_looking_for/replacement_text/g" {} ;');
。 重要的是要注意,我使用 /
作为分隔符,如果要替换的字符串中有斜杠,则必须对其进行转义...... IE /
还有一些其他"仅限Linux"的项目将需要转义,例如$
和@
IE $
和@
另请注意,php
(此外是 Linux 用户www-data
(将需要写入文件的权限。