英文:
Replacement inside var variable: add https:// and port to each IP on a list of somma separated IPs
问题
我有一个包含IP列表的变量,我想在每个IP前面加上http://
,并在末尾加上:8083
。
我的问题类似于这个其他问题:https://stackoverflow.com/questions/65378675/append-port-number-to-each-item-in-comma-separated-list-of-ips,但我不希望每个IP都被引号包围。
raw_ips="100.100.10.10,200.200.10.10,100.201.10.10"
address=magic-happens-here
变量address
应包含:http://100.100.10.10:8083,http://200.200.10.10:8083,http.100.201.10.10:8083
。最好magic-happens-here
是一种类似于上面链接问题中使用的bash替换技巧(因为它更简洁)。
英文:
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: https://stackoverflow.com/questions/65378675/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).
答案1
得分: 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.
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论