Perl替换文件中特定块内的字符串

Perl替换文件中特定块内的字符串,perl,findandmodify,Perl,Findandmodify,您好,我正在尝试用以下字符串替换文件test.txt中的字符串: <g id="g16526"> <g <g id="gnnnnn"> <g 如果它确实具有类似XML的结构,那么应该使用模块来处理它,或者 但如图所示,这项任务也很容易以基本的方式完成 perl -0777 -wpE' BEGIN { $cnt = 0 }; s/<g\nid="g\K(.*?)"/q(g).(++$cnt).q(")/eg

您好,我正在尝试用以下字符串替换文件test.txt中的字符串:

  <g
   id="g16526">
  <g

  <g
   id="gnnnnn">
  <g


如果它确实具有类似XML的结构,那么应该使用模块来处理它,或者

但如图所示,这项任务也很容易以基本的方式完成

perl -0777 -wpE'
    BEGIN { $cnt = 0 };
    s/<g\nid="g\K(.*?)"/q(g).(++$cnt).q(")/eg;
' input.txt
现在正则表达式可以自由地精确地搜索
id=“…”
,我们可以逐行处理


它们都打印预期的输出。为了便于测试,我建议将它们转换为脚本

什么类型的文本文件?如果是XLM-您应该使用XML::Simple来获取id值并替换它。@ilux Re:“您应该使用XML::Simple”。由于许多原因,
XML::Simple
已经被弃用,甚至它自己的文档也建议不要使用它。它在很久以前就有它的地位和重要性,但现在不应该使用它。标准是“XML::LibXML”和
XML::Twig
。谢谢@ilux Re,XML::LibXML或XML::Twig是解决方案。
    #!C:/Strawberry/perl
    open(FILE, "<test.txt") || die "File not found";
    my @lines = <FILE>;
    close(FILE);
    my $string = '<g
    id=';
    my $string2 = '<g
    <g'; 
    my $anything = ".*";

    my $replace = 'gg';
    my @newlines;
    my $counter = 1;

    foreach(@lines) {
      $_ =~ s/\Qstring$anything\Q$string2/$string$replace$string2$counter/g;
      $counter++;
      push(@newlines,$_);
    }

    open(FILE, ">test.txt") || die "File not found";
    print FILE @newlines;
    close(FILE);
perl -0777 -wpE'
    BEGIN { $cnt = 0 };
    s/<g\nid="g\K(.*?)"/q(g).(++$cnt).q(")/eg;
' input.txt
perl -wpE'
    BEGIN { local $/ = "<g"; $cnt = 0 }; 
    s/id="g\K(.*?)"/q(g).++$cnt.q(")/eg; 
' input.txt