2

我有一个像这样的文件Sample:-

206,,,206,14.9,0,2012/04/24 00:00:05
206,,,206,14.9,0,2012/04/24 00:00:21
205,,,205,14.9,0,2012/04/24 00:00:23
205,,,205,14.9,0,2012/04/24 00:00:29
207,,,207,14.9,0,2012/04/24 00:00:34
205,,,205,14.9,0,2012/04/24 00:00:40
204,,,204,14.9,0,2012/04/24 00:00:46
202,,,202,14.9,0,2012/04/24 00:00:52
201,,,201,14.9,0,2012/04/24 00:01:00
202,,,202,14.9,0,2012/04/24 00:01:04

以及以下 AWK 命令:-

awk -F, '{ gsub("/"," ",$7); gsub(":"," ",$7); t+=(mktime($7)-mktime(p)); printf ("%s,%s,%s\n",mktime($7),mktime(p),t); p=$7 }' Sample

给出以下输出:-

1335222005,-1,1335222006
1335222021,1335222005,1335222022
1335222023,1335222021,1335222024
1335222029,1335222023,1335222030
1335222034,1335222029,1335222035
1335222040,1335222034,1335222041
1335222046,1335222040,1335222047
1335222052,1335222046,1335222053
1335222060,1335222052,1335222061
1335222064,1335222060,1335222065

对于每一行,第 7 列将转换为纪元日期,并计算上一行纪元日期之间的差异并将其添加到t.

在正在处理的第一行,因为p当前不是日期,所以 mktime 返回-1扔掉我的数字。

我想要做的是,告诉 AWK 脚本,如果正在处理第 1 行,则假设差为 6。目前它正在从 1335222005 中减去 -1,得到 1335222006。

我想说,从t6 点开始,然后在第二行,计算出与前一行的纪元秒数的差异,并按t该数量递增。

4

3 回答 3

3

你只需要为第 1 行做一些特别的事情。

awk -F, '
    {gsub(/[\/:]/," ",$7); this_time = mktime($7)}
    NR != 1 {t += this_time - prev_time; print this_time, prev_time, t}
    {prev_time = this_time}
' << END

给定您的输入数据,这将打印

1335240021 1335240005 16
1335240023 1335240021 18
1335240029 1335240023 24
1335240034 1335240029 29
1335240040 1335240034 35
1335240046 1335240040 41
1335240052 1335240046 47
1335240060 1335240052 55
1335240064 1335240060 59

或者,初始化变量的一种方便方法是使用 awk'f-v选项

awk -v t=6 '... same as before ...'
于 2012-04-25T18:11:44.487 回答
2

您可以在awk一个块中初始化一个变量BEGIN,并存在两个变量来获取行号,两者都对您的情况有用,FNR并且NR

BEGIN { t = 6 }

或者

FNR == 1 { t = 6 }
于 2012-04-25T17:48:01.983 回答
1

使用BEGIN见这里)有帮助吗?这将允许将 t 变量初始化为您想要的任何内容。就像是

  awk -F, 'BEGIN {t=6} { gsub("/"," ",$7); gsub(":"," ",$7); t+=(mktime($7)-mktime(p)); printf ("%s,%s,%s\n",mktime($7),mktime(p),t); p=$7 }' Sample
于 2012-04-25T17:49:45.253 回答