简体   繁体   English

如何解决此匹配问题并替换Perl文件中仅单词的第n个出现的问题

[英]How to solve this match and replace problem of only nth occurrence of a word in a file in perl

Suppose I have a file which has these few lines 假设我有一个包含以下几行的文件

Hello abc
hii
how are you
Hello abc

If I want to replace the 2nd occurrence of abc by xyz, how can I do? 如果我想用xyz代替abc的第二次出现,该怎么办?

I want an output like 我想要一个输出

Hello abc
hii
how are you
Hello xyz

I tried doing perl -pi -e 's/abc/xyz/ if $. == 2' filename 我尝试做perl -pi -e 's/abc/xyz/ if $. == 2' filename perl -pi -e 's/abc/xyz/ if $. == 2' filename . perl -pi -e 's/abc/xyz/ if $. == 2' filename It is not working for me. 它对我不起作用。 Can anyone help me with this? 谁能帮我这个?

perl -i -pe's/abc/ ++$count == 2 ? "xyz" : "abc" /eg' file

即使abc每行显示多次,此方法也有效。

计算abc出现的时间,如果等于2,则替换为2:

perl -i -pe'$found++ if /abc/; s/abc/xyz/ if $found ==2' filename

I have done it as a script. 我已将其作为脚本完成。 The first argument is the pattern, the second the replacement, the third the number of repetitions and the forth the file, you can also omit the file and insert the data vía stdin. 第一个参数是模式,第二个参数是替换,第三个参数是重复次数,第四个是文件,您也可以省略文件并通过stdin插入数据。

#!/usr/bin/env perl
use v5.28;
my $patt = shift;
my $rep = shift;
my $nth = shift;
my $reps = 0;
while (<>) {
    $reps++ if /$patt/;
    s/$patt/$rep/ if (/$patt/ && $reps == $nth);
    print $_;
}

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

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