首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何从一个大文件中获取最后1000行,然后删除它们?

如何从一个大文件中获取最后1000行,然后删除它们?
EN

Stack Overflow用户
提问于 2018-07-16 00:41:53
回答 2查看 170关注 0票数 1

分两步求解:

获取行:获取行后执行https://stackoverflow.com/a/51350572/8524395

我有一个很大的文件,我想从这个文件的末尾提取1000行,然后删除它们。

我目前使用的是:

代码语言:javascript
复制
function deleteLineInFile($file,$string)
{
    $i=0;
    $array=array();

    $read = fopen($file, "r") or die("can't open the file");
    while(!feof($read)) {
        $array[$i] = fgets($read);  
        ++$i;
    }
    fclose($read);

    $write = fopen($file, "w") or die("can't open the file");
    foreach($array as $a) {
        if(!strstr($a,$string)) fwrite($write,$a);
    }
    fclose($write);
}
$goods = '';
$file = file("../products/".$PidFileName);
for ($i = max(0, count($file)-1001); $i < count($file); $i++) {
    $goods = $goods.$file[$i] . '<br />';
    deleteLineInFile("../products/".$PidFileName, $file[$i]);
}

我想保存我在$goods中得到的行

但是,由于文件大小,它会超时。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-07-16 01:29:07

如果你想从EOF中获得N行,你可以使用SPLFileObject (在PHP5.1中添加):

代码语言:javascript
复制
$num_to_cut = 1000; // must be an integer and not a string
$new_file = new SplFileObject("limited_test.txt", "w");
$old_file = new SplFileObject('test.txt');

// here we get count of lines: go to EOF and get line number
$old_file->seek($old_file->getSize());
$linesTotal = $old_file->key()+1;

// and write data to new file
foreach( new LimitIterator($old_file, $linesTotal-$num_to_cut) as $line) {
    $new_file->fwrite($line);
}
票数 2
EN

Stack Overflow用户

发布于 2018-07-17 16:52:45

要在从大文件中获取行后删除它们,请执行以下操作:

最好的方法是使用sed |,但是如果您没有使用exec()函数的权限,那么这个函数是可以使用的。

代码语言:javascript
复制
function replace_file($path, $string, $replace)
{
    set_time_limit(0);

    if (is_file($path) === true)
    {
        $file = fopen($path, 'r');
        $temp = tempnam('./', 'tmp');

        if (is_resource($file) === true)
        {
            while (feof($file) === false)
            {
                file_put_contents($temp, str_replace($string, $replace, fgets($file)), FILE_APPEND);
            }

            fclose($file);
        }

        unlink($path);
    }

    return rename($temp, $path);
}

函数的来源:https://stackoverflow.com/a/2159135/8524395

要删除这一行,请像这样使用它:

replace_file('myfile.txt', 'RemoveThisPlease', '');

  • 如果您使用了MrSmile的答案来获取行,则将"RemoveThisPlease“替换为$line
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51350234

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档