How to convert YYYYMMDDHHMMSS to a date readable by `date`

前端 未结 6 372
执笔经年
执笔经年 2020-12-07 04:21

I have a set of date/time strings in the YYYYMMDDHHMMSS format that I want to convert to something readable by the date utility. Usually, I can do something li

6条回答
  •  感情败类
    2020-12-07 04:31

    Try this:

    echo "20101106213245" | sed -r 's/^.{8}/& /;:a; s/([ :])(..)\B/\1\2:/;ta'
    

    Result:

    20101106 21:32:45
    
    • Insert a space after the eighth character
    • [label a] After a space or colon and the next two characters, add a colon
    • If a replacement was made, goto label a

    You want some hyphens, too?

    echo "20101106213245" | sed -r 's/^.{4}/&-/;:a; s/([-:])(..)\B/\1\2:/;ta;s/:/-/;s/:/ /'
    

    Result:

    2010-11-06 21:32:45
    
    • Insert a hyphen after the fourth character
    • [label a] After a hyphen or colon and the next two characters, add a colon
    • If a replacement was made, goto label a
    • Change the first colon to a hyphen (2010-11:06:21:32:45 -> 2010-11-06:21:32:45)
    • Change the next colon to a space (2010-11-06:21:32:45 -> 2010-11-06 21:32:45)

提交回复
热议问题