Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Perl in-line edits, how do you insert a line after the Nth occurence of a string?

Looking for a method to insert a line after the Nth occurence of a given string.

The following is close to what I'm looking for, but is line number based, versus based on the Nth occurrence of a given string.

perl -ni -e 'print; print "Put after fifth line\n" if $. == 5' inFile.txt
like image 290
Inetquestion Avatar asked Dec 11 '22 05:12

Inetquestion


1 Answers

The following will add a line of xyz after the second occurrence of the string abc:

perl -pi -e '/abc/&&++$n==2 and $_.="xyz\n"' inFile.txt
like image 83
blhsing Avatar answered Dec 28 '22 22:12

blhsing