bash - 如何使用 bash 和 printf 转换日期格式?

标签 bash awk printf

我要转换2019-02-16Feb 16 15:29在 bash 中使用 awkprintf .

例如:

[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

请提供帮助并解释您的解决方案。

最佳答案

在任何 UNIX 机器上的任何 shell 中使用任何 awk:

$ 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:

$ 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

或者用制表符而不是空格分隔输出:

$ 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:

$ 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 - 如何使用 bash 和 printf 转换日期格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54727591/

相关文章:

bash - 如果前一行下面的行等于第一列的特定值,则打印两行

linux - Bash + 从行中删除空格

c - 强制 printf 忽略格式

c - 为什么我的程序结合了两个 printf 命令?

bash - 在 bash 脚本的循环中使用 nohup

bash - 将序列长度添加到 fasta 文件中的 header

linux - 我想使用 shell 脚本查找存储在文件中的 2 个数字之间的差异

bash - mpc 当前歌曲 bash 脚本故障安全

linux - 将文件名传递给变量时出现命令未找到错误

c - 关于 printf 中的字符串