How can I remove all attributes of p elements in H

2019-08-30 06:02发布

I'd like to remove all attributes of <p> in an HTML file by using this simple Perl command line:

$ perl -pe 's/<p[^>]*>/<p>/' input.html

However, it won't substitute e.g. <p class="hello"> that spans multiple lines such as

<p 
class="hello">

Thus, I attempted to first remove the end of line by doing

# command-1
$ perl -pe 's/\n/ /' input.html > input-tmp.html
# command-2
$ perl -pe 's/<p[^>]*>/<p>/g' input-tmp.html > input-final.html

Questions:

  1. Is there an option in (Perl) regex to try the match across multiple lines?
  2. Can I combine the two commands above (command-1 and command-2) into one? Basically, the first command needs to complete execution before the second one starts.

4条回答
Summer. ? 凉城
2楼-- · 2019-08-30 06:21

-p is short for

LINE: while (<>) {
   ...
} continue {
   print
      or die "-p destination: $!\n";
}

As you can see $_ only contains one line at a times, so the pattern can't possibly match something that spans more than one line. You can fool Perl into thinking the whole file is one line using -0777.

perl -0777 -pe's/<p[^>]*>/<p>/g' input.html

Command line options are documented in perlrun.

查看更多
The star\"
3楼-- · 2019-08-30 06:23

If you write a short script, and put it in its own file, you can easily invoke it using a simple command line.

Improving the following script is left as an exercise:

#!/usr/bin/perl

use warnings; use strict;
use HTML::TokeParser::Simple;

run(\@ARGV);

sub run {
    my ($argv, $opt) = @_;

    my $el = shift @$argv;

    for my $src (@$argv) {
        clean_attribs($src, $el, $opt);
    }
}

sub clean_attribs {
    my ($src, $el, $opt) = @_;
    my $el_pat = qr/^$el\z/;

    my $parser = HTML::TokeParser::Simple->new($src, %$opt);

    while (my $token = $parser->get_token) {
        if ($token->is_start_tag($el_pat)) {
            my $tag = $token->get_tag;
            print "<$tag>";
        }
        else {
            print $token->as_is;
        }
    }
}
查看更多
Ridiculous、
4楼-- · 2019-08-30 06:33
$ perl -pe 's/\n/ /; s/<p[^>]*>/<p>/gs;' input.html > input-final.html
查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-08-30 06:36

perl -pe 'undef $/; s/<p[^>]*>/<p>/g'

查看更多
登录 后发表回答