39

I need to turn the string "125959" into "12:59:59".

Obviously, the string is the time so regular expressions aren't much good here.

Michael Petrotta
  • 58,479
  • 27
  • 141
  • 176
Andrew Mcdonald
  • 415
  • 1
  • 4
  • 8

2 Answers2

78
time=125959
echo ${time:0:2}:${time:2:2}:${time:4:2}
Ansgar Wiechers
  • 184,186
  • 23
  • 230
  • 299
23

I like sed:

time=125959
sed -e "s/\(..\)\(..\)\(..\)/\1:\2:\3/" <<< "$time"
  • You can refine this by replacing . with [[:digit:]]
  • Read about <<< (Here strings) in man bash(1)
Chen Levy
  • 14,088
  • 16
  • 72
  • 90