change the date of month in number format in awk [duplicate]

橙三吉。 提交于 2019-12-13 09:29:56

问题


File 1

P1,06/Jul/2013,09/Jul/2013 
P2,06/Jul/2013,10/Jul/2013 
P3,06/Jul/2013,15/Jul/2013 

Ouput i want like this:

P1,06/07/2013,09/07/2013,3days
P2,06/07/2013,10/07/2013,4days 
P3,06/07/2013,15/07/2013,9days 

some one help is need for this please


回答1:


This answer is heavily dependent on BSD date formatting available on a mac

#!/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 ) )
}

I get the following output:

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:


Try this another awk solution.

#!/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"
}

Output:

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:


With 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


来源:https://stackoverflow.com/questions/17691703/change-the-date-of-month-in-number-format-in-awk

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