I have input data:
foo 24
foobar 5 bar
bar foo 125
and I\'d like to have output:
foo 024
foobar 005 bar
bar foo 125
I doubt that the "if - else" logic can be incorporated in one substitution command without saving the intermediate data (length of the match for instance). It doesn't mean you can't do it easily, though. For instance:
$ N=5
$ sed -r ":r;s/\b[0-9]{1,$(($N-1))}\b/0&/g;tr" infile
foo 00024
foobar 00005 bar
bar foo 00125
It uses recursion, adding one zero to all numbers that are shorter than $N
digits in a loop that ends when no more substitutions can be made. The r
label basically says: try to do substitution, then goto r
if found something to substitute. See more on flow control in sed
here.