Can anyone please tell me how can I search a word in a text file and replace first 2 occurrences with one value and next 2 occurrences with another value and so on using perl script? Is that possible? Below command just replaces all cat1, cat2, cat3 etc. to dog1, but I want to replace cat1,cat2 to dog1 and cat3, cat4 to dog3.
s/cat[0-9]/dog1/g;
Below is the script that I have tried:
#!/usr/bin/perl -w
use strict;
my $file = 'C:\Temp\test.txt';
rename($file, $file . '.bak');
open(IN, '<' . $file . '.bak') or die $!;
open(OUT, '>' . $file) or die $!;
while(<IN>)
{
$_ =~ s/cat[0-9]/dog1/g;
print OUT $_;
}
close(IN);
close(OUT);
Input:
Replacement value1: dog51
Replacement value2: dog23
Replacement value3: dog77
Replacement value4: dog95
Existing File:
<some texts>
test cat01 text
test cat32 text
test cat83 text
test cat54 text
test cat92 text
test cat13 text
test cat62 text
test cat23 text
File after replacement:
<some texts>
test dog51 text
test dog51 text
test dog23 text
test dog23 text
test dog77 text
test dog77 text
test dog95 text
test dog95 text