首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用perl替换文件行中多次出现的单词

使用perl替换文件行中多次出现的单词
EN

Stack Overflow用户
提问于 2019-04-14 23:41:53
回答 1查看 38关注 0票数 -3

需要替换文本文件行中多次出现的单词

代码语言:javascript
复制
#!/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;

实际字符串:

代码语言:javascript
复制
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

预期结果:

代码语言:javascript
复制
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

当前结果:整个段落仅替换为一行。如下所示

代码语言:javascript
复制
first_part this is lesson-1 middle_part this is lesson-1 last_part
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55677099

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档