【问题标题】:Search for text in a 5GB+ file then get whole line在 5GB+ 文件中搜索文本,然后获取整行
【发布时间】:2019-03-27 14:21:44
【问题描述】:

我想在大小为 5GB+ 的 TXT 文件中搜索文本 Hello(示例),然后返回整行。

我尝试过使用SplFileObject,但我知道使用SplFileObject需要行号,就像这样:

$linenumber = 2094; 
$file = new SplFileObject('myfile.txt');
$file->seek($linenumber-1);
echo $file->current();

但如前所述,我想搜索一个字符串然后得到整行,我不知道行号。

任何帮助将不胜感激。

【问题讨论】:

  • 你试过this用一个简单的计数器吗?
  • 你可以用循环逐行读取文件吗?我认为并行化进程可能很有用,例如一个进程从上到下读取,同时另一个进程从下到上读取。
  • 行的大小是多少?您只需要第一次出现,还是所有包含该搜索字符串的行?
  • @programmer-man - 该行大约有 100 个字符,我要查找的字符串也只有一次出现。
  • @RobIII 解决方案似乎是最好的方法。你可以做类似exec('grep "Hello" myfile.txt', $return);

标签: php splfileobject


【解决方案1】:

这应该可行:

<?php
$needle = 'hello';
$count = 1;
$handle = fopen("inputfile.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        // process the line read.
        $pos = strpos($line, $needle);
        if ($pos !== false) {
            echo $line . PHP_EOL;
            echo "in line: ".$count . PHP_EOL;
            break;
        }
        $count++;
    }

    fclose($handle);
} else {
    // error opening the file.
}

【讨论】:

  • 一旦找到while 循环中的break; 行吗?
【解决方案2】:

这是我可以使用的答案。非常感谢@user3783243

对于 Linux:

exec('grep "Hello" myfile.txt', $return);

对于 Windows:

exec('findstr "Hello" "myfile.txt"', $return);

现在$return 应该包含整行。

很遗憾,如果您的服务器管理员在 php.ini 文件中禁用了 exec() 和 system() 功能,这将不起作用。但对我来说效果很好。

如果有人有更好的解决方案,我很高兴知道:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 2015-09-11
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多