【问题标题】:Perl script to search and replace multiple lines in multiple html files用于搜索和替换多个 html 文件中的多行的 Perl 脚本
【发布时间】:2012-10-17 03:59:18
【问题描述】:

我在一个文件夹中有许多 html 文件。我需要以某种方式从所有这些中删除<div id="user-info" ...>...</div>。据我所知,我需要为此使用 Perl 脚本,但我不知道 Perl 会这样做。有人可以帮我拿吗?

下面是“坏”代码的样子:

<div id="user-info" class="logged-in">
    <a class="icon icon-key-delete" href="https://test.dev/login.php?0,logout=1">Log Out</a>
    <a class="icon icon-user-edit" href="https://test.dev/control.php">Control Center</a>


</div> <!-- end of div id=user-info -->

提前谢谢你!

【问题讨论】:

  • 对不起,我无法弄清楚。我之前没有任何 PERL 经验。
  • 提个建议,我们更愿意您尝试自己解决此问题,而不是要求社区为您提供完整的解决方案,即使您的尝试完全失败。谢谢。

标签: regex perl


【解决方案1】:

使用XML::XSH2

for { glob '*.html' } {
    open :F html (.) ;
    delete //div[@id="user-info" and @class="logged-in"] ;
    save :b ;
}

【讨论】:

    【解决方案2】:

    perl -0777 -i.withdiv -pe 's{&lt;div[^&gt;]+?id="user-info"[^&gt;]*&gt;.*?&lt;/div&gt;}{}gsmi;' test.html

    -0777 表示什么都不分割,所以在整个文件中啜饮(而不是逐行,-p 的默认值

    -i.withdiv 表示原地更改文件,保留原始文件,扩展名为 .withdiv(-p 默认只打印)。

    -p 表示逐行传递(除了我们是 slurping)到传递的代码(见 -e)

    -e 期望代码运行。

    man perlrunperldoc perlrun 了解更多信息。

    这是另一种解决方案,了解 jquery 的人会稍微熟悉一些,因为语法类似。这使用 Mojolicious 的 ojo 模块将 html 内容加载到 Mojo::DOM 对象中,对其进行转换,然后打印转换后的版本:

    perl -Mojo -MFile::Slurp -E 'for (@ARGV) { say x(scalar(read_file $_))-&gt;at("#user-info")-&gt;replace("")-&gt;root; }' test.html test2.html test*.html

    直接替换内容:

    perl -Mojo -MFile::Slurp -E 'for (@ARGV) { write_file( $_, x(scalar(read_file $_))-&gt;at("#user-info")-&gt;replace("")-&gt;root ); }' test.html

    注意,这不会只是删除 div,它还会根据 Mojo 的 Mojo::DOM 模块重写内容,因此标签属性的顺序可能不同。具体来说,我看到&lt;div id="user-info2" class="logged-in"&gt;改写为&lt;div class="logged-in" id="user-info2"&gt;

    Mojolicious 至少需要 perl 5.10,但之后就没有非核心要求了。

    【讨论】:

    • 非常感谢!您能告诉我如何制作一个 .pl 文件来执行此操作吗?
    • @user1751343 当心!如果您的div id="user-info" 中有div,这将在您的html 上做一些时髦的事情。
    • 确实如此。使用风险自负。在这种情况下,使用 XML::XSH2 的另一种解决方案将为您提供更正确的结果。
    猜你喜欢
    • 2015-02-20
    • 2021-01-31
    • 1970-01-01
    • 2015-08-24
    • 2018-05-26
    • 2011-02-17
    • 2010-11-05
    • 2013-10-18
    • 2010-09-26
    相关资源
    最近更新 更多