awk convert date format

Could you tell me how to convert the following dates?

If I have m/d/yyyy, I want to have
0m/0d/yyyy. I want my dates to always be 8 digits.

In other words, I want a 0 inserted whenever the month or day is a single digit.

My issue is first I need to use FS="," to get field $4 for the date portion,
within that I need to redefind FS="/" to evaluate the mm and dd portions.

Thanks,
brunc

ex. data

,,,12/6/2012,Harry H,Add,Add,Sys_RTH,111.222.333.777
,,,2/6/2012,Carry H,Add,Add,Sys_RTH,111.222.333.777

desired result.

,,,12/06/2012,Harry H,Add,Add,Sys_RTH,111.222.333.777
,,,02/06/2012,Carry H,Add,Add,Sys_RTH,111.222.333.777
awk -F'[,/]' '{$4=sprintf("%02d/%02d/%d",$4,$5,$6)}1' OFS=, file
awk -F, '{split($4,a,/\//);$4=sprintf("%02d/%02d/%s",a[1],a[2],a[3])}1' OFS=, file

@Yoda, that's assuming that the first 3 comma-separated fields never have any slashes.
And still its a broken solution.

1 Like

My bad, that solution has some gaps, try this instead:

awk -F, '{ split($4,A,"/"); $4=sprintf("%02d/%02d/%d",A[1],A[2],A[3])}1' OFS=, file

---------- Post updated at 12:46 ---------- Previous update was at 12:44 ----------

Thanks elixir. I noticed that later.

The first three fields will not have any slashes, so Yoda's solution works to a point.
Thanks.
But additional month and year are inserted where they shouldn't be.

data:
,,,12/6/2012,Harry H,Add,Add,Sys_RTH,111.222.333.777
,,,2/6/2012,Carry H,Add,Add,Sys_RTH,111.222.333.777

nawk -F'[,/]' '{$4=sprintf("%02d/%02d/%d",$4,$5,$6)}1' OFS=, data

,,,12/06/2012,6,2012,Harry H,Add,Add,Sys_RTH,111.222.333.777
,,,02/06/2012,6,2012,Carry H,Add,Add,Sys_RTH,111.222.333.777

Please use the updated solution, since the first solution that I posted has some issues like the one you mentioned above. Sorry about that.

Worked like a charm, thank you both !:slight_smile:

$ sed -r -e 's_,(.)/_,0\1/_' -e 's_/(.)/_/0\1/_' data
,,,12/06/2012,Harry H,Add,Add,Sys_RTH,111.222.333.777
,,,02/06/2012,Carry H,Add,Add,Sys_RTH,111.222.333.777