需要替换文本文件行中多次出现的单词
#!/usr/bin/perl
use strict;
use warnings;
use Tie::File;
my $string2 = 'first_part';
my $string3 = 'middle_part';
my $string4 = 'last_part';
my @contents=();
tie @contents, 'Tie::File','test.html' or die "Not able to Tie test.html\n";
my $count=1;
foreach (@contents)
{
my $string = $_;
my $quoted_substring = quotemeta($string);
my $before = 'test_example_start';
my $after = 'text_example_end';
if ($string =~ /\Q$before\E(.*?)\Q$after\E/) {
my $finalstr = "$string2$1$string3$1$string4";
s/$quoted_substring/$finalstr/g;
print $finalstr;
}
$count++;
my $finalstr ='';
}
untie @contents;
实际字符串:
test_example_start this is lesson-1 text_example_end where everyone attended the class test_example_start this is lesson-2 text_example_end where two members attended the class test_example_start this is lesson-3 text_example_end where five members attended the class
预期结果:
first_part this is lesson-1 middle_part this is lesson-1 last_part where everyone attended the class first_part this is lesson-2 middle_part this is lesson-1 last_part where two members attended the class first_part this is lesson-1 middle_part this is lesson-3 last_part where five members attended the class
当前结果:整个段落仅替换为一行。如下所示
first_part this is lesson-1 middle_part this is lesson-1 last_part
https://stackoverflow.com/questions/55677099
复制相似问题