如何使用bash和printf转换日期格式? [英] How to convert date format using bash and printf?
本文介绍了如何使用bash和printf转换日期格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用awk
和printf
在bash中将2019-02-16
转换为Feb 16 15:29
.
I want to convert 2019-02-16
to Feb 16 15:29
in bash using awk
and printf
.
例如:
[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
所需的输出:
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.
推荐答案
在任何UNIX盒上的任何shell中使用任何awk:
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}'
例如:
$ 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
如果对齐方式很重要,则有多种解决方案,包括使用printf代替print:
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
或将输出通过管道传输到column -t
:
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
这篇关于如何使用bash和printf转换日期格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文