繁体   English   中英

在多个文件(大数据)中搜索并替换正则表达式

[英]Search and replace regex over multiple files (large data)

我有以下在多个文件中重复的代码:

<tr>
    <th scope="row"> (some php code) </th>
    <td>
         (more php and html)
    </td>
</tr>

tr,th或td标签之前/之后可能会有一些空格。

我将使用什么工具和正则表达式替换以下内容:

<div class="row">
    $1
    $2
</div>

谢谢。

对于第∞ ,请勿使用正则表达式解析HTML。 使用HTML解析器。

在perl中,这意味着使用诸如Web :: Scraper之类的模块。

Perl具有-0777命令行选项,可让您将整个内容读入内存。 完成此操作后,可以使用将\\s*用作空格的替换,它将跨换行边界。 如果使用. ,请确保在替换末尾使用/s

我无法真正说出您要匹配的内容,但是一般原则是:

perl -0777 -i.orig -pe 's/foo/bar/gs' file1 file2 file3

你可以这样做将awk为好。 首先将记录分隔符设置为</tr> ,然后找到开始标签<tr>以及搜索字符串。 假设您的搜索字符串是“更多html代码”。

v="my new string"
awk -vRS="</tr>" -v newstring="$v" '/<tr>/ && /more html code/{ $0=newstring}{print $0>FILENAME}' file 

Perl的另一种选择,类似于您接受的答案

ruby -0777 -i.orig -pe 's/foo/bar/gs' file1 file2 file3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM