perl -pi.bak -e 's/(?<=weak(?:){6})(?=strong)/insert($1)/eig; BEGIN { sub insert { my $name = shift; return "value 8, value 9, value 10"; } }' *.html #### s/ (?<= # Look back-group weak # Match the word weak # tag (?: # Non capturing group ){6} # There are 7 input tags, one already matches, so 6 to go. ) # End look-back (?= # Look-ahead-group strong ) # End look-ahead / the text you want to insert /ixg;