Add a leading zero to date in a file using 'sed' or 'awk'

1564 views awk

I have a file that contains a date in this format (changes every few days)


What I need is to add a zero to the month/day to look like this for single digit months and days.


I found a 'sed' command online however it only adds a zero to the number between '/' and not the first number. Any recommendations?

This is the command:

sed -e 'sx\([^0-9]\)\([0-9]/\)x\10\2xg' -e 'sx/\([0-9]/\)x/0\1xg' /path/to/your/file

answered question

1 Answer


Your first sed stanza will only operate on a date that is preceeded by a character that's not a digit. That won't operate on dates at the start of the line, such as with:

pax$ echo "1/1/2001 1/1/2001" | sed -e 'sx\([^0-9]\)\([0-9]/\)x\10\2xg' -e 'sx/\([0-9]/\)x/0\1xg'
1/01/2001 01/01/2001
pax$ echo " 1/1/2001 1/1/2001" | sed -e 'sx\([^0-9]\)\([0-9]/\)x\10\2xg' -e 'sx/\([0-9]/\)x/0\1xg'
 01/01/2001 01/01/2001

You see there that the first date doesn't change correctly in the first command but does in the second, because it has a space before it.

A quick fix for this is to simply add another clause to handle that case:

-e 'sx^\([0-9]/\)x0\1xg'

posted this

Have an answer?


Please login first before posting an answer.