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 ; }