I want to write a script to insert a string line after finding a match word. There are multiple occurance of match word, but i want to insert at second occurance. How to write the script in perl?
Insert a string line after finding a match
1.3k Views Asked by Pavi At
2
There are 2 best solutions below
0
On
Hope I understood you correctly, try the follows
You can use the regex demo
my $s = "Stack is a linear data structure stack follows a particular order in stack the operations are performed";
$s=~s/(.*?Stack){3}\K//i;
Or you can try with substr also
use warnings;
use strict;
my $match_to_insert = 2; #which match you need to insert
my $f = 1;
while($s=~m/stack/gi)
{
substr($s,$+[0],0) = "\n" , last if($f eq $match_to_insert);
$f++;
}
print "$s\n";
$+[0] which will give the index position of matching string, and I'm making the substr function with that index and I'm inserting the '\n' in that position.
Seeing as your question is unclear to how dynamic or static your script must be and the fact that you did not give any examples, I will only give a simple solution to point you in the right direction. It will search for the word string, then add a newline after it. it also uses the
/gswitch so it will do it globally for allstringwords in the string.From here, I suggest you put some effort into doing some research instead of just expecting everything to be given. You seem to be a perl beginner, so search google for
Perl Tutorialsfor beginners, to get you started.