Replace one digit by two digit using sed

Folks,

Is there a simple way to replace one digit by two digit using sed.

Example,
mydigit1918_2006_8_8_lag1.csv should be
mydigit1918_2006_08_08_lag01.csv.

I tried this way, but doesn't work.
echo mydigit1989_2006_8_8_lag1.csv|sed 's/[[:digit:]]/0[[:digit:]]/'

Thank you,

Apparently your sed doesn't understand the [[:digit:]] class, but if it did, it would replace the first digit -- the 1 in 1989 -- and replace it with a literal string "[[:digit:]]". You need to supply more context; and, apparently, use the old-fashioned [0-9] construct for matching a digit.

echo mydigit1989_2006_8_8_lag1.csv | sed 's/_\([0-9]\)/_0\1/g'

The regular expression matches a single digit after an underscore, and captures it into a backreference so you can refer to it as "\1" in the substitution part. (That's what the backslashed parentheses are for. Your sed might want them without backslashes, or something.) The /g at the end says to do this as many times as possible ("globally"), not just on the first occurrence.

echo mydigit1918_2006_8_8_lag1.csv | sed -e 's/\([^0-9]\)\([0-9]\)\([^0-9]\)/\10\2\3/' -e 's/\([^0-9]\)\([0-9]\)\([^0-9]\)/\10\2\3/g'

Thanks Era,

Your approach looks simple, but not quite right. Shamrock's method below looks long, but it gives me a right answer.

Ah yes, it gets the 2006 too. It's possible to fix that with a different regex but you already have something which works for you.

regexp can be powerful, but can get confusing for the faint hearted

# echo "mydigit1918_2006_08_08_lag01.csv" | awk -F"_" '{$3+=0;$4+=0}1' OFS="_"
mydigit1918_2006_8_8_lag01.csv