gpt4 book ai didi

PHP - 如何在大量文件中替换字符串?

转载 作者:可可西里 更新时间:2023-11-01 00:20:03 24 4
gpt4 key购买 nike

我在服务器上有 200 万个文本文件可供 Internet 用户在线访问。我被要求尽快对这些文件进行更改(字符串替换操作)。我正在考虑对服务器上的每个文本文件执行 str_replace。但是,我不想占用服务器并使其无法被 Internet 用户访问。

您认为以下是个好主意吗?

<?php

ini_set('max_execution_time', 1000);


$path=realpath('/dir/');
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
foreach($objects as $name => $object){
set_time_limit(100);
//do str_replace stuff on the file
}

最佳答案

使用find , xargssed来自 shell,即:

cd /dir

find . -type f -print0 | xargs -0 sed -i 's/OLD/NEW/g

将在当前 dir 中递归搜索所有文件(也隐藏)并使用 sedOLD 替换为 NEW >.


为什么是-print0

来自 man find :

If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the '-print0' option instead of '-print'.


为什么 xargs

来自 man find :

The specified command is run once for each matched file.

也就是说,如果 /dir 中有 2000 个文件,那么 find ... -exec ... 将导致调用 2000 次 sed;而 找到 ... | xargs ... 只会调用 sed 一次或两次。

关于PHP - 如何在大量文件中替换字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29806790/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com