gpt4 book ai didi

linux - 如何将数字打印为 HH MM SS MM DD YYYY?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:57:17 24 4
gpt4 key购买 nike

ls -ltr
-rw-rw-r-- 1 soper sbcprd 36646 Jul 29 21:07 END_TIME_20150729_203759.log
-rw-rw-r-- 1 soper sbcprd 36647 Jul 30 20:37 END_TIME_20150730_201717.log
-rw-rw-r-- 1 soper sbcprd 36643 Jul 31 21:00 END_TIME_20150731_202028.log
-rw-rw-r-- 1 soper sbcprd 36597 Aug 1 16:32 END_TIME_20150801_162901.log
-rw-rw-r-- 1 soper sbcprd 36658 Aug 3 20:53 END_TIME_20150803_202725.log
-rw-rw-r-- 1 soper sbcprd 36645 Aug 4 20:51 END_TIME_20150804_202831.log
-rw-rw-r-- 1 soper sbcprd 36798 Aug 5 20:37 END_TIME_20150805_202013.log

最后一列显示结束时间为 YYYYMMDD_HHMMSS

如何将这些数字打印为 HH MM SS MM DD YYYY

最佳答案

OP 似乎要求重新格式化文件名中指定的时间。因为这些时间与文件的时间戳不同,我们无法通过操作 ls 选项获得我们想要的数字。

使用 sed:

$ ls -ltr | sed -r 's/.*([[:digit:]]{4})([[:digit:]]{2})([[:digit:]]{2})_([[:digit:]]{2})([[:digit:]]{2})([[:digit:]]{2}).log$/\4 \5 \6 \2 \3 \1/'
20 37 59 07 29 2015
20 17 17 07 30 2015
20 20 28 07 31 2015
16 29 01 08 01 2015
20 27 25 08 03 2015
20 28 31 08 04 2015
20 20 13 08 05 2015

或者,如果我们想保留文件名,只需重新格式化名称中的数字:

$ ls -ltr | sed -r 's/([[:digit:]]{4})([[:digit:]]{2})([[:digit:]]{2})_([[:digit:]]{2})([[:digit:]]{2})([[:digit:]]{2})/\4 \5 \6 \2 \3 \1/'
-rw-rw-r-- 1 soper sbcprd 36646 Jul 29 21:07 END_TIME_20 37 59 07 29 2015.log
-rw-rw-r-- 1 soper sbcprd 36647 Jul 30 20:37 END_TIME_20 17 17 07 30 2015.log
-rw-rw-r-- 1 soper sbcprd 36643 Jul 31 21:00 END_TIME_20 20 28 07 31 2015.log
-rw-rw-r-- 1 soper sbcprd 36597 Aug 1 16:32 END_TIME_16 29 01 08 01 2015.log
-rw-rw-r-- 1 soper sbcprd 36658 Aug 3 20:53 END_TIME_20 27 25 08 03 2015.log
-rw-rw-r-- 1 soper sbcprd 36645 Aug 4 20:51 END_TIME_20 28 31 08 04 2015.log
-rw-rw-r-- 1 soper sbcprd 36798 Aug 5 20:37 END_TIME_20 20 13 08 05 2015.log

工作原理

我们使用单个 sed 命令,它是替换。替换命令看起来像 s/old/new/,其中 old 是一个正则表达式,new 可以引用我们在

让我们看看旧的:

  • .* 匹配任何内容,从行首开始。

  • ([[:digit:]]{4}) 匹配四个数字并将它们保存在组 1 中,表示为 \1。今年是

  • ([[:digit:]]{2}) 匹配两个数字并将它们保存在组 2 中,表示为 \2。这是月

  • ([[:digit:]]{2}) 匹配两个数字并将它们保存在第 3 组中,表示为 \3。这一天。

  • _ 匹配下划线字符。

  • ([[:digit:]]{2}) 匹配两个数字并将它们保存在第 4 组中,表示为 \4。现在是时间

  • ([[:digit:]]{2}) 匹配两个数字并将它们保存在第 5 组中,表示为 \5。这是 session 记录。

  • ([[:digit:]]{2}) 匹配两个数字并将它们保存在第 6 组中,表示为 \6。这是秒。

  • .log$ 匹配文件名末尾的 .log

上面匹配的所有内容都替换为 new 中的内容,在我们的例子中,它包括:

  • \4\5\6\2\3\1

    这些是我们在上面匹配但重新排序的六个组。

关于linux - 如何将数字打印为 HH MM SS MM DD YYYY?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32021792/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com