使用Awk或Bash减去两列的值?

时间:2013-04-12 11:18:44

标签: linux bash unix sed awk

这是我的档案:

$ 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

我已经尝试了一切......提前感谢! =)

3 个答案:

答案 0 :(得分:1)

有时候有必要留下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

答案 1 :(得分:0)

基于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

答案 2 :(得分:0)

使用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