Converting dates in AWK

后端 未结 3 997
轻奢々
轻奢々 2020-12-05 14:32

I have a file containing many columns of text, including a timestamp along the lines of Fri Jan 02 18:23 and I need to convert that date into MM/DD/YYYY H

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-05 15:13

    you can try this. Assuming just the date you specified is in the file

    awk '
    {
        cmd ="date \"+%m/%d/%Y %H:%M\" -d \""$1" "$2" "$3" "$4"\""
        cmd | getline var
        print var
        close(cmd)
    }' file
    

    output

    $ ./shell.sh
    01/02/2010 18:23
    

    and if you are not using GNU tools, like if you are in Solaris for example, use nawk

    nawk 'BEGIN{
       m=split("Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec",d,"|")
       for(o=1;o<=m;o++){
          months[d[o]]=sprintf("%02d",o)
       }
       cmd="date +%Y"
       cmd|getline yr
       close(cmd)
    }
    {
        day=$3
        mth=months[$2]
        print mth"/"day"/"yr" "$4
    } ' file
    

提交回复
热议问题