34

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
  • 56,954
  • 26
  • 136
  • 173
Andrew Mcdonald
  • 365
  • 1
  • 3
  • 8

2 Answers2

69
time=125959
echo ${time:0:2}:${time:2:2}:${time:4:2}
Ansgar Wiechers
  • 175,025
  • 22
  • 204
  • 278
19

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
  • 12,926
  • 16
  • 67
  • 86