加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 21:53:39 所属栏目:PHP教程 来源:网络整理
导读:我在互联网用户可在线访问的服务器中有两百万个文本文件.我被要求尽快对这些文件进行更改(字符串替换操作).我正在考虑在服务器上的每个文本文件上执行str_replace.但是,我不想绑定服务器并让互联网用户无法访问它. 你认为以下是个好主意吗? ?phpini_set('ma
我在互联网用户可在线访问的服务器中有两百万个文本文件.我被要求尽快对这些文件进行更改(字符串替换操作).我正在考虑在服务器上的每个文本文件上执行str_replace.但是,我不想绑定服务器并让互联网用户无法访问它.

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

<?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,xargs和 sed,即:

cd /dir

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

将在当前目录内递归搜索所有文件(也隐藏),并使用sed将OLD替换为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个文件,则查找… -exec …将导致2000次调用sed;而找到… | xargs …只会调用sed一次或两次.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读