[英]Replace every nth Occurrence in a Perl Script
I have text file with 10 lines. 我有10行的文本文件。 Each line has the word no_access and only that in it.
每行中都有单词no_access,并且其中仅包含单词。 I found a website that has syntax to replace every nth occurrence of some string.
我发现了一个网站,该网站的语法可以替换每n次出现的某个字符串。 When I try to put it into a script, it spits out errors.
当我尝试将其放入脚本中时,会吐出错误。
Replace every Nth occurrence 每N次替换一次
This is the script I have so far: 这是我到目前为止的脚本:
use strict;
use warnings;
while (<>) {
my $count = 0;
s/no_access/(++$count % 3 == 0)?"read":$&/ge;
}
print;
However, I get the error: Use of uninitialized value $_ in print. 但是,我收到错误:在打印中使用未初始化的值$ _。
I tried the script without the print command, but nothing happens. 我尝试了没有print命令的脚本,但是什么也没有发生。 How do I get this script to run and perform the replacement of every third "no_access".
如何使此脚本运行并执行每三个“ no_access”的替换。
Here's another option: 这是另一个选择:
use strict;
use warnings;
my $i = 0;
my $n = 3;
while (<>) {
s/no_access/read/ if !( ++$i % $n );
print;
}
Usage: perl script.pl inFile [>outFile]
用法:
perl script.pl inFile [>outFile]
The last, optional parameter directs output to a file. 最后一个可选参数将输出定向到文件。
Hope this helps! 希望这可以帮助!
Your code is almost correct, just move the variable declaration outside the while loop, and the print inside: 您的代码几乎是正确的,只需将变量声明移到while循环外,然后将打印内容移到里面:
use strict;
use warnings;
my $count = 0;
while (<>) {
s/no_access/(++$count % 3 == 0)?"read":$&/ge;
print;
}
It then reads from stdin and prints to stdout, changing every 3rd occurrence as you want it to. 然后,它从stdin读取并打印到stdout,根据需要更改每个第3次出现的值。
If you want to read in a file, change its contents, then write it again, your code could look like this: 如果要读取文件,更改其内容,然后再次写入,则代码可能如下所示:
use strict;
use warnings;
my $file = $ARGV[0];
die "usage: $0 <filename>" unless defined $file;
open(IN, "<$file") or die "Can't read $file: $!";
my $count = 0;
my $out = "";
while (<IN>) {
s/no_access/(++$count % 3 == 0)?"read":$&/ge;
$out .= $_;
}
close(IN);
open(OUT, ">$file") or die "Can't write $file: $!";
print OUT $out;
close(OUT);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.