簡體   English   中英

使用Awk或Bash減去兩列的值?

[英]Subtract the Values of Two Columns Using Awk or Bash?

這是我的檔案:

$ cat myfile.txt 
48700039|09:39:58|09:40:34
48700040|09:59:12|09:59:42
48700041|10:01:08|10:05:47
48700042|10:50:53|10:51:24

我想從3中減去第2列,所以我的期望輸出是:

48700039|09:39:58|09:40:34|00:00:36
48700040|09:59:12|09:59:42|00:00:30
48700041|10:01:08|10:05:47|00:04:39
48700042|10:50:53|10:51:24|00:00:31

我已經嘗試了一切...預先感謝! =)

有時,有必要離開awk / sed / bash的美好世界,而轉入能夠理解時間的腳本語言。 這樣的場合。

#!/usr/bin/env python

from datetime import datetime

FMT = '%H:%M:%S'

with open("myfile.txt") as fd:
    for line in fd:
        line = line.strip()
        t = line.split('|')
        tdelta = datetime.strptime(t[2], FMT) - \
                datetime.strptime(t[1], FMT)

        print "%s|%s" % (line, tdelta)

輸出:

48700039|09:39:58|09:40:34|0:00:36
48700040|09:59:12|09:59:42|0:00:30
48700041|10:01:08|10:05:47|0:04:39
48700042|10:50:53|10:51:24|0:00:31

基於GNU awk(gawk)的解決方案:

gawk -F"|" 'BEGIN {DT="2000 01 01 "} { gsub(/:/, " "); t1=mktime(DT $2);
      t2=mktime(DT $3); gsub(/ /, ":"); print $0"|"strftime("%T", t2-t1, "UTC") }'

現場演示: http//ideone.com/VZ1DPD

使用sed和date,

while read line;do
    #extraction of the columns 2 and 3 && converting them into an array
    d=($(echo $line | sed -e 's/\(.*\)|\(.*\)|\(.*\).*/\2\n\3/')) 
    #substraction of dates
    datediff=$(($(date -d ${d[0]} +%s)-$(date -d ${d[1]} +%s))) 
    #absolute value
    datediff=${datediff/-/}
    #print the line and the 'extra' H:M:S
    printf "%s|%02d:%02d:%02d\n" $line $((datediff/3600)) $((datediff%3600/60)) $((datediff%60))
done < myfile.txt

輸出:

48700039|09:39:58|09:40:34|00:00:36
48700040|09:59:12|09:59:42|00:00:30
48700041|10:01:08|10:05:47|00:04:39
48700042|10:50:53|10:51:24|00:00:31

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM