问题
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