Martin Pavlik
Martin Pavlik

Reputation: 16

awk convert quoted timestamp to specific date time format

I need to convert unix timestamp value (in the first field of lof file) to specific date time format (%m/%d/%Y %H:%M:%S.%3N)

To give you an example. I have a log file looking like this

"1456316486","1000","11678","0.00","0.00","0.00","0.00","1","0.00","0.00","1792364","652108","8.02","0.00","0.00","0.00","0","remmina"

and I need it to look like this

"02/24/2016 13:21:26.000","1000","11678","0.00","0.00","0.00","0.00","1","0.00","0.00","1792364","652108","8.02","0.00","0.00","0.00","0","remmina"

to be able to import it into another tool.

P.S. I am aware of the fact there is a bunch of examples how to do this, but as an awk n00b I was not able to get it to do exactly what I want.

thanks for any help

Upvotes: 0

Views: 1521

Answers (3)

Lars Fischer
Lars Fischer

Reputation: 10149

I tried mpez0 elegant solution with the $1+0, but for me it didn't work. I had to explicitly remove the " from $1 before the strftime, and so I came up with this solution for GNU-Awk 4.0.1:

awk -v FS=, -v OFS=, '{gsub(/"/,"",$1 ); $1 = strftime("\"%D %T.000\"",$1); print; }' file
  • %D means %m/%d/%y and %T means %H:%M:%S
  • I could not find a format for the milliseconds, so I put a fixed .000 in
  • setting the input field separator and the output field separator with the -v to get input and output separated with ,

Upvotes: 2

Ed Morton
Ed Morton

Reputation: 203334

With GNU awk for strftime:

$ awk 'BEGIN{FS=OFS="\""} {$2=strftime("%D %T.000")} 1' file
"02/26/16 07:53:29.000","1000","11678","0.00","0.00","0.00","0.00","1","0.00","0.00","1792364","652108","8.02","0.00","0.00","0.00","0","remmina"

Upvotes: 1

mpez0
mpez0

Reputation: 2883

If you're using a recent version of awk with timestamp extensions over the original (which you likely are), then

timestr = strftime("%m/%d/%Y %T.000", $1+0)

should give the string you want. You need the +0 to convert from the string of digits to a number.

Upvotes: 0

Related Questions