使用awk将日期文件转换为unix时间 [英] Converting a file of dates into unix time with awk

查看:206
本文介绍了使用awk将日期文件转换为unix时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含日期和经纬度的文件,我想将UTC中的日期转换为unix时间.我决定在awk脚本中使用unix date函数来执行此操作.我尝试过:

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

其中,t是文件中的第三行,格式为2014182120311.我是awk/scripting的新手,不确定是否可以将awk变量嵌入到awk行内的unix命令中.

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.

运行脚本时出现错误:

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

所以我认为我没有正确定义"t".任何帮助深表感谢!

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

另一方面,我尝试了mktime和其他awk时间函数,但我认为它们对我不起作用,因为我没有gawk.

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.

推荐答案

是否不能选择安装gawk?稍后您会感谢您(例如,参见使用bash将日期列表从文件转换为时间戳记).

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).

BEGIN部分在打开任何文件之前执行,因此$3(从当前文件读取的当前记录的第三个字段)在该部分中没有意义,因此t=$3只是设置变量t为空字符串.

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.

您不想打印命令,c,您想打印由getline读取的执行命令的结果,但是当您使用无向getline时,它将覆盖$ 0,$ 1等,因此您应该将结果保存到var中(请参见 http://awk.info/?tip/getline )

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.

这篇关于使用awk将日期文件转换为unix时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆