问题
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