Insert a string line after finding a match

1.3k views Asked by At

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?

2

There are 2 answers

0
mkHun 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.

0
Gerhard On

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 /g switch so it will do it globally for all string words in the string.

use strict;
use warnings;

my $str = "this is my string";
   $str=~s/string/string\nAnother string/g;
   print $str;

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 Tutorials for beginners, to get you started.