0

I have a file that contains dates and lat longs and I want to convert the dates that are in UTC to unix time. I decided to use the unix date function within an awk script to do this. I tried:

awk 'BEGIN {t=$3; c="date -j -f %Y%j%H%M%S "t" +%s"; c|getline; close( c ); print $1, $2, c; }' test.txt

where t is the third row in my file and is in the format 2014182120311. I am new to awk/scripting and not sure if it is possible to imbed an awk variable into a unix command inside an awk line.

When I run the script I get the error:

usage: date [-jnu] [-d dst] [-r seconds] [-t west] [-v[+|-]val[ymwdHMS]] ... 
        [-f fmt date | [[[mm]dd]HH]MM[[cc]yy][.ss]] [+format]

So I think I am not defining "t" properly. Any help is much appreciated!

On a side note- I have tried mktime and the other awk time functions but they do not work for me I believe because I do not have gawk.

krodmannix
  • 845
  • 10
  • 30
Kim B
  • 3
  • 2

1 Answers1

0

Do you not have the option of installing gawk? You'll thank yourself later (e.g. see Converting list of dates from a file to timestamp with bash).

The BEGIN section is executed before any file is opened, so $3 (the 3rd field of the current record read from the current file) has no meaning in that section and so t=$3 just sets the variable t to the null string.

You don't want to print the command, c, you want to print the result of executing the command as read by getline but when you use undirected getline it overwrites $0, $1, etc. so you should save the result in a var (see http://awk.info/?tip/getline).

You probably want something like this:

awk '{
    cmd = "date -j -f %Y%j%H%M%S " $3 " +%s"
    if ( (cmd | getline time) > 0 ) {
        print $1, $2, time
    }
    close(cmd)
}' test.txt

but if not, post some sample input and expected output so we can help you.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185
  • 1
    Your above example gives the result I was looking for- the logic makes a lot more sense this way. Will look into installing gawk. Thanks! – Kim B Aug 28 '14 at 13:38