use strict; my $count = 1; while (<>) { if ( m/^\^sip/ ) { s[ ## No need to explicitly capture anything (?<=\s) ## 2nd last num field cannot be 4 digits \d{1,3} ## only this is replaced. (?= \s+ \d+ $ ) ## Ensure there's one more before the EOS ][$count]x; $count++; } print ; } #### use strict; my $count = 1; while (<>) { if ( m/^\^sip/ ) { s[ ( (?: \S+ \s+ ){17} ) ## Capture the 17/34 fields to $1 \d{1,3} ## No need to capture (?= \s+ \d+ $ ) ## Ensure there's one more before the EOS ][$1$count]x; $count++; } print ; }