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
  • 59,888
  • 27
  • 145
  • 179
Andrew Mcdonald
  • 415
  • 1
  • 4
  • 8

2 Answers2

81
time=125959
echo "${time:0:2}":"${time:2:2}":"${time:4:2}"
bvargo
  • 103
  • 3
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
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
  • 15,438
  • 17
  • 74
  • 92