在awk中以数字格式更改月份的日期

时间:2013-07-17 05:20:38

标签: awk gawk nawk awk-formatting

档案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 

请为此提供一些帮助

3 个答案:

答案 0 :(得分:1)

这个答案在很大程度上取决于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

答案 1 :(得分:0)

尝试另一个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

答案 2 :(得分:0)

使用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