Skip to main content
3 of 4
fix a typo and grammar; pruned more words
Jeff Schaller
  • 68.8k
  • 35
  • 122
  • 264

How to split a string into an array in bash

I have a problem with the output of a program. I need to launch a command in bash and take its output (a string) and split it to add new lines in certain places. The string looks like this:

battery.charge: 90 battery.charge.low: 30 battery.runtime: 3690 battery.voltage: 230.0 device.mfr: MGE UPS SYSTEMS device.model: Pulsar Evolution 500

basically it is an xxx.yy.zz: value, but the value may contain spaces. Here's the output I'd like to get

battery.charge: 90
battery.charge.low: 30
battery.runtime: 3690
battery.voltage: 230.0
device.mfr: MGE UPS SYSTEMS
device.model: Pulsar Evolution 500 

I have an idea to search for first dot and then look back from that position for space to put a new line there, but I'm not sure how to achieve it in Bash. I'm still a beginner.

user67524
  • 83
  • 1
  • 1
  • 3