$ cat prog.pl use strict; use warnings; my $cnt = 1; while (<>) { s/$/sprintf '%04d', $cnt++/e if /^\*+$/; print; } $ $ $ cat file.txt foo boo *** goo hoo *********************************** bloo $ $ $ perl prog.pl file.txt foo boo ***0001 goo hoo ***********************************0002 bloo $