0

Need to append ports to lists of ips via bash script.

Sample input:

ip="100.100.10.10,200.200.10.10,100.201.10.10"
port="123"

Expected output: "100.100.10.10:123","200.200.10.10:123","100.201.10.10:123"

I got it to: "100.100.10.10","200.200.10.10","100.201.10.10" using hosts="\"${ip//,/\",\"}\"" but can't get the ":$port" appended to each ip. Would prefer to append it in the same hosts= script rather than adding more script conditions.

oguz ismail
  • 1
  • 16
  • 47
  • 69
Mike
  • 75
  • 7

1 Answers1

4

Using just Bash you can replace the , by ":$port," and then add the port and the closing double-quote for the last IP address:

$ echo "\"${ip//,/:$port\",\"}:$port\""
"100.100.10.10:123","200.200.10.10:123","300.300.10.10:123"
tripleee
  • 175,061
  • 34
  • 275
  • 318
photonic.bean
  • 344
  • 2
  • 10
  • 1
    updated answer to add double-quotes in the output – photonic.bean Dec 20 '20 at 10:16
  • Please don't revert my edits to add quoting. We already get too many questions where someone copy/pastes sloppy code which seemed to work with trivial strings, and wonder why it doesn't also work with their less trivial strings. See also [When to wrap quotes around a shell variable?](https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable) – tripleee Dec 20 '20 at 10:24
  • The revert was accidental. I submitted my edit after you edited because I haven't refreshed the page yet. Anyway, IP addresses doesn't contain white-spaces and the replace command as it is suggested in the answer doesn't allow white-spaces around the comma, so there's no actual need to wrap everything in quotes. – photonic.bean Dec 20 '20 at 10:27
  • 1
    Thanks photonic.bean. Was beating my head on this. – Mike Dec 20 '20 at 10:32
  • Indeed, this code will seem flawless until you try it with different inputs, like I already alluded in my previous comment. – tripleee Dec 20 '20 at 10:33