文件 1
P1,06/Jul/2013,09/Jul/2013
P2,06/Jul/2013,10/Jul/2013
P3,06/Jul/2013,15/Jul/2013
输出我想要这样:
P1,06/07/2013,09/07/2013,3days
P2,06/07/2013,10/07/2013,4days
P3,06/07/2013,15/07/2013,9days
请为此提供一些帮助
这个答案在很大程度上取决于 mac 上可用的 BSD 日期格式
#!/usr/bin/awk -f
BEGIN { FS=" " }
{
split( $0, arr, "," )
ts1 = date2ts( arr[ 2 ] )
ts2 = date2ts( arr[ 3 ] )
days = (ts2-ts1)/86400
date1 = ts2date( ts1 )
date2 = ts2date( ts2 )
printf( "%s,%s,%s,%d days\n", arr[ 1 ], date1, date2, days )
}
function runCmd( cmd ) {
cmd | getline output
close( cmd )
gsub( "\"", "", output )
return output
}
function date2ts( date ) {
return runCmd( sprintf( \
"date -j -f\\\"%%d/%%b/%%Y\\\" \\\"%s\\\" +\\\"%%s\\\"", date ) )
}
function ts2date( ts ) {
return runCmd( sprintf( \
"date -j -f\\\"%%s\\\" \\\"%s\\\" +\\\"%%d/%%m/%%Y\\\"", ts ) )
}
我得到以下输出:
P1,06/07/2013,09/07/2013,3days
P2,06/07/2013,10/07/2013,4days
P3,06/07/2013,15/07/2013,9days
试试这个另一种awk
解决方案。
#!/usr/bin/awk
BEGIN {
FS=",";
}
{
epoch_date_format($2)|getline d1
epoch_date_format($3)|getline d2
days=(d2-d1)/3600/24;
month_format(d1)|getline sd1
month_format(d2)|getline sd2
print $1","sd1","sd2","days"days"
}
function epoch_date_format( string ) {
split(string,array,"/");
return "date -d\""array[1]"-"array[2]"-"array[3]"\" +%s";
}
function month_format( epoch ) {
return "date -d@"epoch" +%d/%m/%Y"
}
输出:
P1,06/07/2013,09/07/2013,3days
P2,06/07/2013,10/07/2013,4days
P3,06/07/2013,15/07/2013,9days
使用 GNU awk:
awk -F'[,/]' -v OFS=',' '
function date2secs(fld) {
return mktime($(fld+1)" "(match("JanFebMarAprMayJunJulAugSepOctNovDec",$fld)+2)/3" "$(fld-1)" 0 0 0")
}
{
start= date2secs(3)
end = date2secs(6)
diff = int((end-start)/(60*60*24))
print $1,strftime("%d/%m/%Y",start),strftime("%d/%m/%Y",end),diff"days"
}
' file
P1,06/07/2013,09/07/2013,3days
P2,06/07/2013,10/07/2013,4days
P3,06/07/2013,15/07/2013,9days