鉴于我有以下 awk 脚本:
#!/usr/bin/awk -f
BEGIN {
startTimestamp = ARGV[1];
endTimestamp = ARGV[2];
print startTimestamp
print endTimestamp
print startTimestamp + 60 seconds
print endTimestamp + 10 minutes
}
我想为给定参数添加秒或分钟:startTimestamp
和endTimestamp
。
例如,我可以调用此脚本,./print-timestamps.awk 2018-10-14T13:26:00.000 2018-10-14T13:27:50.000
并且我希望打印:
2018-10-14T13:26:00.000
2018-10-14T13:27:50.000
2018-10-14T13:27:00.000
2018-10-14T13:37:50.000
我怎样才能做到这一点?
答案1
GNUawk
有mktime
和strftime
:
$ gawk '{gsub(/[-T:]/," "); print strftime("%Y-%m-%dT%H:%M:%S\n", mktime($0)+60)}'
$ gawk '
function timeadd(t, s){
gsub(/[-T:]/," ", t); return strftime("%Y-%m-%dT%H:%M:%S", mktime(t)+s)
}
BEGIN{
print ARGV[1]
print ARGV[2]
print timeadd(ARGV[1], 60)
print timeadd(ARGV[2], 60 * 10)
}
' 2018-10-14T13:26:00.000 2018-10-14T13:27:50.000
2018-10-14T13:26:00.000
2018-10-14T13:27:50.000
2018-10-14T13:27:00
2018-10-14T13:37:50
它的一个版本timeadd
也处理毫秒:
$ cat timeadd.awk
function timeadd(t, s){
gsub(/[-T:]/," ", t)
t = mktime(t) + s + substr(t, index(t, "."))
s = substr(sprintf("%.3f", t - int(t)), 2)
return strftime("%Y-%m-%dT%H:%M:%S" s, t)
}
{ print timeadd($1, $2); }
$ gawk -f /tmp/timeadd.awk
2018-10-19T13:26:58.815 4.237
2018-10-19T13:27:03.052
2018-10-19T13:26:58.122 -3.822
2018-10-19T13:26:54.300
答案2
GNUdate
可用吗?尝试
awk '
BEGIN {
startTimestamp = ARGV[1];
endTimestamp = ARGV[2];
print startTimestamp
sub (/T/, " ", startTimestamp)
print endTimestamp
sub (/T/, " ", endTimestamp)
system ("date +\"%FT%T\" -d\"" startTimestamp " 60 seconds\"")
system ("date +\"%FT%T\" -d\"" endTimestamp " 60 minutes\"")
} ' 2018-10-14T13:26:00.000 2018-10-14T13:27:50.000
2018-10-14T13:26:00.000
2018-10-14T13:27:50.000
2018-10-14T13:27:00
2018-10-14T14:27:50