1

这是我的文件:

$ 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

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

4

3 回答 3

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
于 2013-04-12T12:14:56.133 回答
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

于 2013-04-12T13:19:18.807 回答
0

使用 sed 和日期,

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
于 2014-06-23T09:45:29.110 回答