2012-10-26 39 views
-1

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

这里是 “坏” 的代码的样子:

<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 --> 

预先感谢您!

+0

http://stackoverflow.com/questions/1030787/multiline-search-replace-with-perl – alestanis

+0

对不起,我无法弄清楚。我之前没有任何PERL经验。 – user1751343

+0

只是一个建议的话,我们更喜欢你是否试图自己解决这个问题,而不是要求社区为你提供一个完整的解决方案,即使你的尝试完全被破坏了。谢谢。 – Kev

回答

1

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

-0777意味着没有分裂,所以通过线在整个文件啜(而不是线,为-p

-i.withdiv手段改变文件的默认到位后,保留原有扩展名.withdiv(默认为-p仅打印)。

-p表示通过逐行(除了我们正在sl咽)通过代码(参见-e)

-e需要代码运行。

man perlrunperldoc perlrun欲了解更多信息。

这里的另一种解决方案,这将是轻微到jQuery的认识,因为语法类似人们比较熟悉。这将使用Mojolicious' ojo模块加载HTML内容成魔精:: DOM对象,改造它,然后打印转换后的版本:

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

直接替换内容:

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

注意,这不会只需删除该div,它也将重新编写基于Mojo的Mojo :: DOM模块的内容,因此标记属性可能不是相同的顺序。具体来说,我看到<div id="user-info2" class="logged-in">改写为<div class="logged-in" id="user-info2">

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

+0

非常感谢!你能告诉我如何让一个.pl文件来做到这一点? – user1751343

+1

@ user1751343小心!如果你的'div id =“user-info”里面有'div',这会在你的html上做些时髦的事情。 – alestanis

+0

这是非常真实的。使用风险自负。另一种解决方案,使用XML :: XSH2将在这种情况下给你更正确的结果。 – kbenson

3

使用XML::XSH2

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