PHP - 如何在大量文件中进行字符串替换?
PHP - How to do a string replace in a very large number of files?
我在服务器上有 200 万个文本文件可供 Internet 用户在线访问。我被要求尽快对这些文件进行更改(字符串替换操作)。我正在考虑对服务器上的每个文本文件执行 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
}
不要用 PHP 这样做,它很可能会严重失败,我会占用你所有的系统资源。
find . -type f -exec sed -i 's/search/replace/g' {} +
上面的示例使用搜索和替换字符串及其递归和常规文件,包括隐藏文件。
使用 shell
中的 find, xargs and sed,即:
cd /dir
find . -type f -print0 | xargs -0 sed -i 's/OLD/NEW/g
将在当前 dir
中递归搜索(也隐藏)所有文件,并使用 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个文件,那么find ... -exec ...
将导致sed
调用2000次;而 find ... | xargs ...
只会调用 sed
一次或两次。
您也可以使用仅限于一个核心(默认)的 Python 程序来执行此操作。如果你的机器有多个内核,并且至少有一个通常是空闲的,你应该设置。
我在服务器上有 200 万个文本文件可供 Internet 用户在线访问。我被要求尽快对这些文件进行更改(字符串替换操作)。我正在考虑对服务器上的每个文本文件执行 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
}
不要用 PHP 这样做,它很可能会严重失败,我会占用你所有的系统资源。
find . -type f -exec sed -i 's/search/replace/g' {} +
上面的示例使用搜索和替换字符串及其递归和常规文件,包括隐藏文件。
使用 shell
中的 find, xargs and sed,即:
cd /dir
find . -type f -print0 | xargs -0 sed -i 's/OLD/NEW/g
将在当前 dir
中递归搜索(也隐藏)所有文件,并使用 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个文件,那么find ... -exec ...
将导致sed
调用2000次;而 find ... | xargs ...
只会调用 sed
一次或两次。
您也可以使用仅限于一个核心(默认)的 Python 程序来执行此操作。如果你的机器有多个内核,并且至少有一个通常是空闲的,你应该设置。