在 Linux 環境下處理日誌、影片時長、工時統計等需求時,常需將多筆 HH:MM:SS 格式時間相加。本文提供一個 AWK 腳本,正確處理秒→分、分→時的進位邏輯,並輸出總時間。
#!/usr/bin/awk -f
BEGIN {
FS = ":"; # 輸入欄位分隔符
OFS = ":"; # 輸出欄位分隔符
}
{
# 累加秒數
total_seconds += $3;
# 秒數進位到分
if (total_seconds >= 60) {
total_seconds -= 60;
$2 += 1;
}
# 累加分數(含進位)
total_minutes += $2;
# 分數進位到時
if (total_minutes >= 60) {
total_minutes -= 60;
$1 += 1;
}
# 累加時數
total_hours += $1;
}
END {
# 最後再處理一次總計的進位(避免中間遺漏)
if (total_seconds >= 60) {
total_minutes += int(total_seconds / 60);
total_seconds = total_seconds % 60;
}
if (total_minutes >= 60) {
total_hours += int(total_minutes / 60);
total_minutes = total_minutes % 60;
}
printf "%02d:%02d:%02d\n", total_hours, total_minutes, total_seconds;
}
time_sum.awk,賦予執行權限:chmod +x time_sum.awktimes.txt,每行一筆 HH:MM:SS:01:30:45
00:45:30
02:15:10
./time_sum.awk times.txt → 輸出 04:31:25FS=":" 將每行拆為 $1=時、$2=分、$3=秒。$1/$2/$3 會被修改,若輸入行數極多,中間累計值可能再次超過 60,故在 END 以總和再做一次模數運算,確保最終結果正確。printf "%02d:%02d:%02d" 保證兩位數補零。若需顯示天數,可在 END 區塊加入:
days = int(total_hours / 24);
hours = total_hours % 24;
if (days > 0) printf "%d天 ", days;
printf "%02d:%02d:%02d\n", hours, total_minutes, total_seconds;
$3 為空,建議前置 NF==3 過濾。AWK 處理欄位式文字資料極為強大,配合 BEGIN/END 模式與算術運算,幾行程式碼即可完成時間累加與進位。掌握此技巧,日常日誌分析與統計將更加得心應手。