Como adicionar segundos ou minutos a um determinado timestamp no AWK

1

Dado que tenho o seguinte script awk:

#!/usr/bin/awk -f

BEGIN {
  startTimestamp = ARGV[1];
  endTimestamp = ARGV[2];

  print startTimestamp
  print endTimestamp
  print startTimestamp + 60 seconds
  print endTimestamp + 10 minutes
}

Gostaria de adicionar segundos ou minutos a determinados argumentos: startTimestamp e endTimestamp .

por exemplo. Eu posso chamar esse script com ./print-timestamps.awk 2018-10-14T13:26:00.000 2018-10-14T13:27:50.000 e esperaria imprimir:

2018-10-14T13:26:00.000
2018-10-14T13:27:50.000
2018-10-14T13:27:00.000
2018-10-14T13:37:50.000

Como posso fazer isso?

    
por Patrik Mihalčin 17.10.2018 / 11:57

2 respostas

3

O% GNUawk tem mktime e 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

Uma versão de timeadd que também lida com milissegundos:

$ 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
    
por 17.10.2018 / 14:08
0

O GNU date está disponível? Experimente

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
    
por 17.10.2018 / 13:38

Tags