-2

I have a variable with a list of IPs, and I want to replace each IP with http:// at the beginning and :8083 at the end.

My question is similar to this other question: Append port number to each item in comma separated list of IPs but I don't want each IP to be surrounded by quotes each.

raw_ips="100.100.10.10,200.200.10.10,100.201.10.10"
address=magic-happens-here

The variable address should contain: http://100.100.10.10:8083,http://200.200.10.10:8083,http://100.201.10.10:8083. It's preferable that the magic-happens-here is some bash substitution trick similar to the one used on the linked-to question above (because of its brevity).

ABu
  • 10,423
  • 6
  • 52
  • 103
  • 2
    You have to do it in two steps. Add `:8083` just like in the linked question. Add `http://` similarly, but you put it *after* each comma instead of before, and an extra one at the beginning instead of the end. – Barmar Apr 10 '23 at 17:58
  • If you understand how that solution worked, it should have been straightforward to extend it to this. – Barmar Apr 10 '23 at 17:59
  • And if you don't, you should try to learn. Programming isn't done by copying solutions, you need to learn the underlying principles so you can do it yourself. You're a human being, not ChatGPT. – Barmar Apr 10 '23 at 18:00
  • @Barmar Despite its similarities with sed I didn't really understand "how" exactly the solution worked with so many escapes and slashes because the linked-to answer didn't mention the name of the syntax. Now I found it's one of the so called bash substring replacement syntaxis. Thank you. – ABu Apr 10 '23 at 18:11
  • I don't know how exactly you are going to use your list, but perhaps a more maintainable approach would be to convert your list into an array, then loop over the array and make the required transformation on each array element (which then is trivial). – user1934428 Apr 11 '23 at 07:40

1 Answers1

1

It was straightforward once I knew the syntax is called "substring replacement", in its flavour for regular patterns, whose syntax (for each match and not just the first one) is ${var//pattern/replacement}. It can be done in one line with:

raw_ips="100.100.10.10,200.200.10.10,100.201.10.10"
address="http://${raw_ips//,/:8083,http://}:8083"

It replaces each , with :8083,http://, together with an initial http:// and a final :8083 to fill the head and the tail of the list.

Cyrus
  • 84,225
  • 14
  • 89
  • 153
ABu
  • 10,423
  • 6
  • 52
  • 103
  • 1
    in the general case, you need to test `raw_ips` is not empty otherwise your substitution can be incorrect – jhnc Apr 10 '23 at 19:47
  • @jnhc Thank you for the tip, but in our case it won't be empty for sure. – ABu Apr 11 '23 at 14:15