mtmacdonald
mtmacdonald

Reputation: 15090

How to use strftime function multiple times in an awk command

I want to use gawk to convert unix timestamps to a date format, using strftime.

When I use strftime once, I get the expected result:

$ echo 1454310000 | gawk -F "," '{$s=strftime("%Y-%m-%d %H:%M:%S", ($1), 1); $e=$s; print ($s, $e);}'
2016-02-01 07:00:00 2016-02-01 07:00:00

But when I use strftime multiple times, both returned results are completely wrong:

$ echo 1454310000 | gawk -F "," '{$s=strftime("%Y-%m-%d %H:%M:%S", ($1), 1); $e=strftime("%Y-%m-%d %H:%M:%S", ($1), 1); print ($s, $e);}'
1970-01-01 00:33:36 1970-01-01 00:33:36

Why is this happening and how do I correct it so I can use strftime twice on the same input?

Upvotes: 0

Views: 1097

Answers (2)

fedorqui
fedorqui

Reputation: 289835

The problem here is the usage of variables. In awk, variables are not referred with a leading dollar. So say yes to var and say no to $var:

$ echo 1454310000 | gawk -F "," '{s=strftime("%Y-%m-%d %H:%M:%S", ($1), 1); e=strftime("%Y-%m-%d %H:%M:%S", ($1), 1); print (s, e);}'
2016-02-01 07:00:00 2016-02-01 07:00:00

What was happening?

Since s and e were undefined variables, when you said $s=something(), you ended up assigning the output of that something() into $ plus an undefined variable value, which defaults to 0. And $0 is the whole record, so you were assigning the value of the record itself.

See a simpler example:

$ echo "hello" | awk '{$s="bu"; print}'
bu

Upvotes: 1

Georg P.
Georg P.

Reputation: 3164

You don't need the '$' symbols to dereference variables. Try that:

echo 1454310000 | gawk -F "," '{s=strftime("%Y-%m-%d %H:%M:%S", ($1), 1); e=strftime("%Y-%m-%d %H:%M:%S", ($1), 1); print (s, e);}'

Upvotes: 0

Related Questions