Calculate date difference between $2,$3 from file in awk

倖福魔咒の 提交于 2019-12-02 11:16:12

问题


I would need your help.

File with only date,

file.txt

P1,2013/jul/9,2013/jul/14 
P2,2013/jul/14,2013/jul/6 
P3,2013/jul/7,2013/jul/5 

display output like this

P1,2013/jul/9,2013/jul/14,5days
P2,2013/jul/14,2013/jul/6,8days 
P3,2013/jul/7,2013/jul/5,2days

回答1:


awk '
    BEGIN {
        months = "jan feb mar apr may jun jul aug sep oct nov dec"
        OFS = FS = ","
    }
    function date2time(date,     a,mon) {
        split(date, a, "/")
        mon = 1 + (index(months, a[2])-1)/4
        return mktime(a[1] " " mon " " a[3] " 0 0 0")
    }
    function abs(n) {
        return n<0 ? -n : n
    }
    function diff_days(d1,d2,    delta) {
        delta = date2time(d1) - date2time(d2)
        return int(abs(delta)/86400)
    }

    { print $0, diff_days($2, $3) "days" }
'
P1,2013/jul/9,2013/jul/14 ,5days
P2,2013/jul/14,2013/jul/6 ,8days
P3,2013/jul/7,2013/jul/5 ,2days



回答2:


I don't think mktime() is the best option for this problem. I would go with external date command:

awk -F'[,/]' '{
"date -d\""$3"-"$4"-"$2"\" +%s"|getline d1
"date -d\""$6"-"$7"-"$5"\" +%s"|getline d2
x=d1-d2; x=x<0?-x:x;x/=3600*24;
print $0","x" days"
 }' file

output

P1,2013/jul/9,2013/jul/14 ,5 days
P2,2013/jul/14,2013/jul/6 ,8 days
P3,2013/jul/7,2013/jul/5 ,2 days


来源:https://stackoverflow.com/questions/17670093/calculate-date-difference-between-2-3-from-file-in-awk

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!