PFD
PFD

Reputation: 17

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

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

1/5/2016

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

01/05/2016

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

Upvotes: 0

Views: 992

Answers (1)

paxdiablo
paxdiablo

Reputation: 881553

In terms of what you're doing wrong, your first sed stanza will only operate on a date that is preceeded by a character that's not a digit. That means it won't operate on dates at the start of the line since there's no character before it.

See the following transcript:

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 character before it.

A quick fix for this is to simply add another clause to handle that start-of-line case:

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

You could also switch to extended regular expressions if your sed supports it, and modify the first stanza to handle both cases (non-digit or start anchor):

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

This also lets you get rid of some of those ugly backslashes :-)

Of course, if all your dates are at the start of the line, or you have one date at the start of the line in a one-line file (your first paragraph seems to imply this), it becomes a lot simpler:

pax$ echo "1/1/2001" | awk -F/ '{printf "%02d/%02d/%04d\n", $1, $2, $3}'
01/01/2001

Upvotes: 1

Related Questions