awk - change date format

I have below date format in a CSV file. (dd/mm/yyyy)
Ex Input:
9/8/2013

Need to convert it into below format (yyyymmdd ) and redirect to new file.
Ex Output:
20130809

How do I use awk here to change the format and if leading 0 (zero) is not then add it.
Please help. Thanks.

What is the format of the csv file?

Check this one

echo 9/8/2013 | awk -F/ '{printf "%s%02s%02s\n", $3, $2, $1}'
1 Like

Worked! thanks a lot :slight_smile:

---------- Post updated at 01:15 AM ---------- Previous update was at 12:35 AM ----------

I am not able to use awk for this, can anyone please help?

input csv file record (there will be 50k records in one file)

number, number, date time, number
123456789,98765432,9/8/2012 3:00,1

Need output:
date , time , number , number, number
20130809,030000,123456789,98765432,1

Need to convert date and time and put it in first position. How do i do it? Please advise. Thanks.

awk -F'[,| |/|:]' 'NR>1{printf "%s%02s%02s,%02s%s00,%d,%d,%d\n",$5,$4,$3,$6,$7,$1,$2,$NF; }' file.csv
1 Like

Thanks for your reply.... this is working for the data I gave... but in actual file i also have strings with spaces and it could have : / as well.... but file is comma separated.

eg:
Input file:

number,      number,   date time,  number, string, string
123456789,98765432,9/8/2012 3:00,1, ABC ABC, NEW STRING (12/3)

Need output:

   date , time ,            number ,    number,   number, string, string
20130809,030000,123456789,98765432,1, ABC ABC, NEW STRING (1:23)

Please advise. Sorry for not giving complete data before!

So is the transformation of xy/z to x:yz supposed to occur in both string fields or only in the last field? Will that transformation always be for 2 digits followed by a slash followed by a single digit, or is there some more general pattern?

PLEASE use code tags as demanded!
I expect your specification to change again, for the 4th time, e.g. to accomodate for fields in double quotes as normally used in .csv files. And, how and why did field 6 change from ...12/3 to 1:23?
Why don't you give it a try yourself, having seen so many examples in the replies to your posts? Anyhow, use this as a starting point:

$ awk -F, '{split($3, Dt, "[/ :]"); printf "%4d%02d%02d,%02d%02d00,%s,%s,%s,%s,%s\n", Dt[3],Dt[2],Dt[1],Dt[4],Dt[5],$1,$2,$4,$5,$6}' file
20120809,030000,123456789,98765432,1, ABC ABC, NEW STRING (12/3)
1 Like

Below solution worked! Thanks all for ur help.

awk -F , '{
          
        split($3,a," ")
        var1=a[1]
        var2=a[2]
        split(var1,a,"/")s    ### Separate date
        printf("%02s%02s%02s,",a[3],a[2],a[1])
        split(var2,b,":")      ### Separate time
        printf("%02s%02s00, ,",b[1],b[2])
        ### End of date and time

        printf("%s,%s,%s, , ,0,%s, , , ,I, , , ,\n",$1,$2,$4,$7)
            
         }' a.csv