How to convert date format using bash and printf?

…衆ロ難τιáo~ 提交于 2020-08-08 05:48:12

问题


I want to convert 2019-02-16 to Feb 16 15:29 in bash using awk and printf.

For example:

[root@localhost ~]# who | awk '{print $1, $3, $4}'
root 2019-02-16 15:29
root 2019-02-16 15:30
john 2019-02-01 10:34
emmett 2019-01-12 09:45

Desired output:

root Feb 16 15:29
root Feb 16 15:30
john Feb 1  10:34
emmett Jan 12 09:45

Please help and provide an explanation with your solution.


回答1:


With any awk in any shell on any UNIX box:

$ who | awk '{split($3,d,/-/); print $1, substr("JanFebMarAprMayJunJulAugSepOctNovDec",(d[2]*3)-2,3), d[3]+0, $4}'

For example:

$ cat file
root 2019-02-16 15:29
root 2019-02-16 15:30
john 2019-02-01 10:34
emmett 2019-01-12 09:45

$ awk '{split($2,d,/-/); print $1, substr("JanFebMarAprMayJunJulAugSepOctNovDec",(d[2]*3)-2,3), d[3]+0, $3}' file
root Feb 16 15:29
root Feb 16 15:30
john Feb 1 10:34
emmett Jan 12 09:45

and if alignment matters there's various solutions, including using printf instead of print:

$ awk -v OFS='\t' '{split($2,d,/-/); printf "%s %s %-2d %s\n", $1, substr("JanFebMarAprMayJunJulAugSepOctNovDec",(d[2]*3)-2,3), d[3]+0, $3}' file
root Feb 16 15:29
root Feb 16 15:30
john Feb 1  10:34
emmett Jan 12 09:45

or separate the output with tabs instead of blanks:

$ awk -v OFS='\t' '{split($2,d,/-/); print $1, substr("JanFebMarAprMayJunJulAugSepOctNovDec",(d[2]*3)-2,3), d[3]+0, $3}' file
root    Feb     16      15:29
root    Feb     16      15:30
john    Feb     1       10:34
emmett  Jan     12      09:45

or pipe the output to column -t:

$ awk '{split($2,d,/-/); print $1, substr("JanFebMarAprMayJunJulAugSepOctNovDec",(d[2]*3)-2,3), d[3]+0, $3}' file | column -t
root    Feb  16  15:29
root    Feb  16  15:30
john    Feb  1   10:34
emmett  Jan  12  09:45



回答2:


You can use strftime()

$ who | awk '{print $1}' | awk -F '[-]' '{ print $1, strftime ("%b %d %H:%M", systime()) }'



回答3:


Employ strftime(,mktime()) within gawk, using a non-character regular expression Field Separator (-F flag):

your_output |gawk -F'\\W' '
    {print $1 , strftime("%b %d %H:%M",mktime($2 " " $3 " " $4 " " $5 " " $6 " 00"))}
'

Roughly what was said above, alas following with your IO with mktime() syntax.



来源:https://stackoverflow.com/questions/54727591/how-to-convert-date-format-using-bash-and-printf

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