1

I have browsed through the similar threads and they helped me come closest to what I want to do but didn't fully answer my question.

I have a date in the format dd/mm/yyyy hh:mm:ss ($mydate = 26/12/2013 09:42:42) that I want to convert in unix timestamp via the command:

date -d $mydate +%s

But here the accepted format is this one: yyyy-mm-dd hh:mm:ss

So I did this transformation:

echo $mydate| awk -F' ' '{printf $1}'| awk -F/ '{printf "%s-%s-%s\n",$3,$2,$1}'

And have this ouput:

2013-12-26

Which is good, now I try to append to hour part before doing the conversion:

echo $mydate| awk -F' ' '{printf $1; $hour=$2}'| awk -F/ '{printf "%s-%s-%s %s\n",$3,$2,$1,$hour}'

But then I have this:

2013-12-26 26/12/2013

It seem to not keep the variable $hour.

I am new in awk, how could I do this ?

fedorqui
  • 275,237
  • 103
  • 548
  • 598

2 Answers2

1

In awk you can use a regex as a field separator. In your case instead of using awk twice you may want to do the following:

echo $mydate| awk -F' |/' '{printf "%s-%s-%s %s",$3,$2,$1,$4}'

With this we use both space and / as separators. First 3 parts are the date field, 4th one is time which lies after space.

alexK
  • 963
  • 1
  • 7
  • 17
0

The thing here is that you are "losing" the time block when you say awk '{print $1}'.

Instead, you can use a single awk command like:

awk -F'[: /]' '{printf "%d-%d-%d %d:%d:%d", $3, $2, $1, $4, $5, $6}'

This slices the record based on either :, / or space and then puts them back together in the desired format.

Test:

$ echo "26/12/2013 09:42:42" | awk -F'[: /]' '{printf "%d-%d-%d %d:%d:%d", $3, $2, $1, $4, $5, $6}'
2013-12-26 9:42:42

Then store it in a var and use date -d: formatted_date=$(awk '...'); date -d"$formatted_date".

fedorqui
  • 275,237
  • 103
  • 548
  • 598