unix中的时间戳数据操作

时间:2015-03-09 18:05:07

标签: linux bash unix awk

我有一个csv数据文件,它有两个时间戳字段 - start_time和end_time。它们是"2014-02-01 00:06:22"形式的字符串。数据文件的每一行都是具有多个字段的记录。该文件非常小。

我想计算所有记录的平均持续时间。除了使用shell脚本之外,是否有任何单行命令可以用于这种简单的计算,可能使用awk?

我对awk很新。这是我的所作所为,但不起作用。 $6$7是start_time和end_time的字段。

awk -F, 'BEGIN { count=0 total=0 }
    { sec1=date +%s -d $6 sec2=date +%s -d $7
    total+=sec2-sec1 count++} 
    END {print "avg trip time: ", total/count}' dataset.csv

csv文件示例:

"start_time","stop_time","start station name","end station name","bike_id"
"2014-02-01 00:00:00","2014-02-01 00:06:22","Washington Square E","Stanton St & Chrystie St","21101"

1 个答案:

答案 0 :(得分:1)

将GNU awk用于mktime()和gensub():

$ cat tst.awk
BEGIN { FS="^\"|\",\"" }
function t2s(time) { return mktime(gensub(/[-:]/," ","g",time)) }
NR>1 { totDurs += (t2s($3) - t2s($2)) }
END { print totDurs / (NR-1) }

$ gawk -f tst.awk file
382

使用其他awks,您需要调用shell date函数:

$ cat tst2.awk
BEGIN { FS="^\"|\",\"" }
function t2s(time,      cmd,secs) {
    cmd = "date +%s -d \"" time "\""
    if ( (cmd | getline secs) <= 0 ) {
        secs = -1
    }
    close(cmd)
    return secs
}
NR>1 { totDurs += (t2s($3) - t2s($2)) }
END { print totDurs / (NR-1) }

$ awk -f tst2.awk file                               
382