简体   繁体   中英

Replace every nth Occurrence in a Perl Script

I have text file with 10 lines. Each line has the word no_access and only that in it. I found a website that has syntax to replace every nth occurrence of some string. When I try to put it into a script, it spits out errors.

Replace every Nth occurrence

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. How do I get this script to run and perform the replacement of every third "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]

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:

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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