我正在使用Perl来实现这一点。
while(<INFILE>){
        chomp;
         if(/\<td/){
          system("perl -i -e 's/<td/<td bgcolor="blue"/g' $_");
          }
}当我运行该命令时,我得到
./HtmlTest.pl file.html
Bareword found where operator expected at ./HtmlTest.pl line 13, near ""perl -i -e 's/<td/<td bgcolor="grey"
        (Missing operator before grey?)
String found where operator expected at ./HtmlTest.pl line 13, near "grey"/g' $_""
syntax error at ./HtmlTest.pl line 13, near ""perl -i -e 's/<td/<td bgcolor="grey"
Execution of ./HtmlTest.pl aborted due to compilation errors.我想不出为什么
即使我以
perl HtmlTest.pl file.html我得到了同样的错误。
示例html表
 <td>ABC</td>
 <td>DEF</td>
 <td>20:00:00</td>感谢您的任何建议
发布于 2020-09-05 03:14:52
当涉及到解析复杂的HTML文件时,正则表达式可能会变得效率低下,更好的做法是使用专用的HTML解析器。下面是一个使用XML::LibXML的示例,假设您有一个有效的HTML文件:
use strict;
use warnings;
use XML::LibXML;
my $filename = 'file.html';
my $html = XML::LibXML->load_html( location  => $filename );
for my $node ($html->findnodes('//td')) {
    $node->setAttribute(bgcolor => "blue");
}
print $html->toStringHTML;发布于 2020-09-05 02:24:13
我认为您需要转义字符串中的",因为它会报告"near "grey"/g' (假设您在代码中尝试使用grey )
因为整个字符串是:"perl -i -e '<string_no_quotes>' $_" if string_no_quotes has“,它会给出这个错误,所以需要对它进行escpaed。
更新:
如果像这样的代码行得通,你可以把它写成stdout,然后通过管道把它传送到文件中。
foreach my $i ('<td>ABC</td>', '<td>DEF</td>', '<td>20:00:00</td>', '<h1>test</h1>') {
  chomp;
  
  $_ = $i;
  if (/\<td/) {
      print 's/<td/<td bgcolor="blue"/g';
   } else {
      print $_;
   }
}我用for循环替换了while循环,这样我就可以在在线解析器中测试它。我使用的是这样的:https://www.tutorialspoint.com/execute_perl_online.php
发布于 2020-09-05 11:12:20
在OPs代码中,我们有下面这一行,应该将其更正为下一形式
system("perl -i -e 's/<td/<td bgcolor=\"blue\"/g' $_");这是错误的,$_将保留从<INFILE>读取的当前行,但它将期望输入文件。
下面的代码演示了不使用任何模块的替代解决方案。这个解决方案也不是最好的。
use strict;
use warnings;
while( <DATA> ) {
    s/<td>/<td bgcolor="blue">/;
    print;
}
__DATA__
<block>
  Some text goes in this place
</block>
 <td>ABC</td>
 <td>DEF</td>
 <td>20:00:00</td>
 
 <p>
    New paragraph describing something
 </p>更正确的方法是外部CSS样式的style='some_style',而不是使用bgcolor="blue"。
这种方法将允许在不接触html文件的情况下对所需标签的样式文件进行改变。
你用你想要的样式编辑CSS样式文件,神奇的是,你的网页将显示新的颜色/文本样式/列表类型/等等。
https://stackoverflow.com/questions/63746029
复制相似问题