This is another way to express radoulov's answer
awk '/foo/ {sub(/foo/, "&_" sprintf("%02d",++c))} 1' infile
You must ensure that you do not match "foobar" when searching for "foo":
gawk '/\<foo\>/ {sub(/\<foo\>/, "&_" sprintf("%02d",++c))} 1'
source
share