awk - problems by converting date-format

Hi

i try to change the date-format from DD/MM/YYYY into MM/DD/YY .
Input-Data:

...
31/12/2013,23:40,198.00,6.20,2,2,2,1,11580.0,222
31/12/2013,23:50,209.00,7.30,2,2,3,0,4380.0
01/01/2014,00:00,205.90,8.30,2,2,3,1,9360.0,223
...

Output-Data should be:

...
12/31/13,23:40,198.00,6.20,2,2,2,1,11580.0,222
12/31/13,23:50,209.00,7.30,2,2,3,0,4380.0
01/01/14,00:00,205.90,8.30,2,2,3,1,9360.0,223
...

i try to do it with awk ....

awk -F'[,|/]' '{ printf "%2d/%02d/%02d,%s,%s,%s\n" $2,$1,$3,$NF}' 

but awk "ran out" -- i have still not understand, what awk do with the tripple %s. can someone help me please.

Thanks in advance,
IMPe

"%2d/%02d/%02d,%s,%s,%s\n" is expecting 6 arguments, and you only have 4 (and 11 or 12 fields on the lines).

One way might be to use split rather than having multiple field separators:

awk '{split($1,d,"/"); $1=d[2]"/"d[1]"/"d[3]; print}' FS=OFS=, file
1 Like

Hi CarloM,

Thanks a lot for your fast reply. Your "split-version" is working pretty good, but the the Year has still four numbers.
It is possible, to combine it with something like substr(d[3],3,2) ?

awk '{split($1,d,"/"); $1=d[2]"/"d[1]"/"(substr(d[3],3,2)); print}' FS=OFS=, file

only give me the formated date in MM/DD/YY.
I'm still try to become more familliar with awk and i suppose split will help me several times more in the future.

Thanks,
IMPe

I suspect d[3] may actually be the rest of the line. Try setting FS & OFS separately.

awk '{split($1,d,"/"); $1=d[2]"/"d[1]"/"(substr(d[3],3,2)); print}' FS=, OFS=, file
1 Like

Could be done with simple sed statements like:

sed 's!\(..\)/\(..\)!\2/\1!' yourfile

or

sed 's!\(...\)\(...\)!\2\1!' yourfile
1 Like

CarloM and ctsgnb, to both of you a big thank you.

ctsgnb --> this sed-command will change the "position" of dd/mm to mm/dd but it will not reduce YYYY to YY. finally i want to compare the time-stamp with data from another file, so i need the year-format absolutly like YY.

Thanks,
IMPe

 sed 's#\(..\)/\(..\)/..\(..\)#\2/\1/\3#' file

You can then go for :

sed 's!\(...\)\(...\)..!\2\1!' yourfile

or (a little more "secure")

sed 's!\(../\)\(../\)..!\2\1!' yourfile

Note that when you go from YYYY to YY you loose information and may lead to ambiguous situation (12 could be 1912 or 2012 ...) even if the range of data you work with, will most probably be 2012 than 1912, it is always better to think of potential issue before than after :wink:
Maybe it would be better to convert the YY into YYYY in the other file instead ?? ...

1 Like