Zero pad numbers in `cal` (or `gcal`) output

bashcommand lineunix

This seemed pretty easy, but I have not found a good way to do it.

In Terminal, cal will give this output:


September 2015
Su Mo Tu We Th Fr Sa
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30

That is, it will show the calendar for the current month.

I would like to have it display like so:


September 2015
Su Mo Tu We Th Fr Sa
01 02 03 04 05
06 07 08 09 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30

This seems like it would be fairly easy to do, but so far I can’t crack it.

Initially I thought I would just look for the numbers 1-9 with one space on either side. That works… except if the number is on Saturday, or Sunday, because then there's no leading/trailing padding.

So I'm at a loss. I even looked at GNU cal which seems to have a bazillion options, but I couldn't find one for this.

I'm sure there's a way to do this with sed/awk/tr/etc but I can't figure it out. Would prefer as “lightweight” of a solution as possible, as this is something that will run frequently, but I'm not adverse to installing something else via brew if it can do a better/ more efficient job.

Best Answer

sed to the rescue:

pse@Mithos:~$ cal 09 2015 | sed -e 's/ \([[:digit:]]\) /0\1 /g' \
                                -e 's/ \([[:digit:]]\)$/0\1/g'
   September 2015
Su Mo Tu We Th Fr Sa
      01 02 03 04 05
06 07 08 09 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30

Combining the two sed commands into one is left as an exercise to the reader.