awk:创建具有递增值的列
我有一个文本文件,有3列,像这样awk:创建具有递增值的列,awk,Awk,我有一个文本文件,有3列,像这样 2010-01-03 11:00:00 -134 2010-01-03 11:01:00 -131 2010-01-03 11:02:00 -128 ... 现在我需要以秒为单位的时间步长,而不是现有的时间步长 如何创建一个介于$2和$3之间的新列,填充递增的值(0、60、120…),直到文件结束?根据您的声明和数据,您可能需要: awk '{ print $1, $2, i*60, $3; i++;}' orifil
2010-01-03 11:00:00 -134
2010-01-03 11:01:00 -131
2010-01-03 11:02:00 -128
...
现在我需要以秒为单位的时间步长,而不是现有的时间步长
如何创建一个介于$2和$3之间的新列,填充递增的值(0、60、120…),直到文件结束?根据您的声明和数据,您可能需要:
awk '{ print $1, $2, i*60, $3; i++;}' orifile
另一种解决方案是在
awk
awk '$3=(NR-1)*60 FS $3' file
你得到
2010-01-03 11:00:00 0 -134
2010-01-03 11:01:00 60 -131
2010-01-03 11:02:00 120 -128
2010-01-03 11:00:00 0 -134
2010-01-03 11:01:00 60 -131
2010-01-03 11:02:00 120 -128
关于罗罗的回答,略短一点的版本:
awk'{print$1,$2,(NR-1)*60,$3}'orifile
假设时间戳并非都是均匀分布的,您必须解析它们:使用GNU awk您可以使用mktime
来实现这一点:
gawk '{ ts = $1 " " $2; gsub(/[-:]/, " ", ts); t = mktime(ts) } NR == 1 { start = t } { $2 = $2 OFS (t - start); } 1'
这项工作如下:
{ # for all lines:
ts = $1 " " $2 # concat first and second fields,
gsub(/[-:]/, " ", ts) # replace - and : with spaces. The result is the
# format mktime expects: "YYYY MM DD HH MM SS"
t = mktime(ts) # convert to seconds since Epoch
}
NR == 1 { # in the first line:
start = t # set the starting point
}
{ # for all lines:
$2 = $2 OFS (t - start) # append the seconds since start to the second field,
# effectively inserting a third
}
1 # then print.
干得也不错。我只是需要它。