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?
-
2Your question is ambiguous, lacking example of what you're trying to achieve, and most of all shows absolutely no effort from your side to solve it. Good luck with that. – mpapec Sep 13 '17 at 09:41
-
1What have you tried? What problems are you having? Please show us your code. If you don't have any code then Stack Overflow is probably the wrong place to ask your question. – Dave Cross Sep 13 '17 at 09:54
2 Answers
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.

- 22,678
- 7
- 27
- 43
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.

- 5,891
- 8
- 38
- 85