如何使用 awk 從列中減去日期?

如何使用 awk 從列中減去日期?

我有這樣的三列:

18:37:12 18:37:31 0  
18:37:01 18:37:18 0

我想讓第三列填充前兩列的秒數差異,如下所示:

18:37:12 18:37:31 19  
18:37:01 18:37:18 17

我正在使用這個:

nova migration-list | grep completed | awk '{ print substr($22,12,8), substr($24,12,8) }' | awk 'BEGIN{ FS=" " } { print $0, $2-$1 }'

我很感激任何幫助

答案1

在 GNU 系統上:

awk '{"date -d "$1" +%s"|getline one; "date -d "$2" +%s"|getline two; \
         print $1, $2, two-one}' file.txt
  • "date -d "$1" +%s"|getline one取得欄位 1 自紀元以來的秒數(使用 GNU date),保存在變數中one

  • "date -d "$2" +%s"|getline two對欄位 2 執行相同操作,並將結果儲存為變數two

  • print $1, $2, two-one列印字段一、二以及變數二和一的減法

例子:

% cat file.txt
18:37:12 18:37:31 0
18:37:01 18:37:18 0

% awk '{"date -d "$1" +%s"|getline one; "date -d "$2" +%s"|getline two; print $1, $2, two-one}' file.txt
18:37:12 18:37:31 19
18:37:01 18:37:18 17

答案2

使用 GNU awk 的內建時間函數:

awk '
  function to_time(time,   t,a) {
    split(time, a, ":")
    t = mktime("1970 1 1 " a[1] " " a[2] " " a[3])
    return t
  }
  {print $1, $2, to_time($2) - to_time($1)}
' file

相關內容