我需要你的帮助。
仅包含日期的文件,
file.txt的
P1,2013/jul/9,2013/jul/14
P2,2013/jul/14,2013/jul/6
P3,2013/jul/7,2013/jul/5
显示这样的输出
P1,2013/jul/9,2013/jul/14,5days
P2,2013/jul/14,2013/jul/6,8days
P3,2013/jul/7,2013/jul/5,2days
答案 0 :(得分:4)
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
答案 1 :(得分:1)
我认为mktime()
不是解决此问题的最佳选择。我会选择外部日期命令:
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
输出
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