繁体   English   中英

查找-替换字符串的多次出现并附加迭代数字

[英]Find-Replace Multiple Occurrences of a string and append iterating number

我如何遍历html文件的代码并查找某些重复出现的文本,然后在其上附加单词和迭代数字。

So: 
<!-- TemplateBeginEditable -->
<!-- TemplateBeginEditable -->
<!-- TemplateBeginEditable -->   
etc...                    

Becomes :
<!-- TemplateBeginEditable Event=1 -->
<!-- TemplateBeginEditable Event=2 -->
<!-- TemplateBeginEditable Event=3 -->
etc...

我尝试过PERL认为这将是最简单/最快的,然后转到jQuery,然后再回到PERL。

用REGEX查找/替换许多方法并返回出现的数组似乎很简单,但是要添加迭代变量证明是更大的挑战。

我尝试过的最新示例:

#!/usr/bin/perl -w

# Open input file 
open INPUTFILE, "<", $ARGV[0] or die $!;
# Open output file in write mode
open OUTPUTFILE, ">", $ARGV[1] or die $!;

# Read the input file line by line
while (<INPUTFILE>) {
  my @matches = ($_ =~ m/TemplateBeginEditable/g);
  ### what do I do ith matches array? ###
  $_ =~ s/TemplateBeginEditable/TemplateBeginEditable Event=/g;
  print OUTPUTFILE $_; 

}


close INPUTFILE;
close OUTPUTFILE;

要执行替换,您不需要先匹配模式,就可以直接执行替换。 您的代码示例:

while (<INPUTFILE>) {
    s/TemplateBeginEditable/TemplateBeginEditable Event=/g;
    print OUTPUTFILE $_; 
}

现在,要添加在每次替换时递增的计数器,您可以使用以下语法在模式本身中放入一段代码:

my $i;

while (<INPUTFILE>) {
    s/TemplateBeginEditable(?{ ++$i })/TemplateBeginEditable Event=$i/g;
    print OUTPUTFILE $_; 
}

要使其更短,您可以使用\\K功能来更改匹配结果的开始:

while (<INPUTFILE>) {
    s/TemplateBeginEditable\K(?{ ++$i })/ Event=$i/g;
    print OUTPUTFILE $_; 
}

或单线:

perl -pe 's/TemplateBeginEditable\K(?{++$i})/ Event=$i/g' file > output

如果您有可用的awk ,并且目标文本每行最多仅出现一次,那么我认为Perl是过大的:

awk 'BEGIN{n=1}{n+=sub("TemplateBeginEditable","& Event="n)}1'

一些解释: sub返回执行的替换数(0或1); &表示“任何匹配项”; "..."n是字符串连接(awk中没有运算符); 1是“ true”条件,它调用{print}的默认“ action”。

在评论中扩展我的一线:

#!/usr/bin/perl
use strict;
use warnings;

my $file = shift or die "Usage: $0 <filename>\n";

open my $fh, '<', $file or die "Cannot open $file: $!\n";
open my $ofh, '>', "$file.modified" or die "Cannot open $file.modified: $!\n";

my $i = 1;
while (my $line = <$fh>) {
   if ($line =~ s/TemplateBeginEditable/$& Event=$i/) {
      $i++;
   }
   print $ofh $line;
}

__END__

请注意,这假设您不会像一行示例中所示的那样,在一行上包含多个所需文本实例。

我会做:

local $/=undef;
my $content = <FH>;
my $x = 0;
$content =~ s/(My expected pattern)/$1 . " time=" . (++$x)/ge;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM