Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Bash: convert comma seperated ips into array of ip

I am getting comma seperated IPs as a string in my application from terraform. I need to replace variable in a conf file with array of ips. Number ips can be anything. I have taken 2 as an example.

Script.sh:

#!/bin/bash
var_ips="10.10.10.177,10.10.10.181"

IFS=','
read -ra ip_array <<< "$var_ips"
form_hosts=()
for item in "${ip_array[@]}";do
     form_hosts+=("\"$item\"")
done 

sed -i "s/^hosts: \"from_terraform_hosts\"$/hosts: [${form_hosts[*]}]/g" host.conf

host.conf

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

hosts: "from_terraform_hosts"
//file truncated

Here i want entry in host.conf as

hosts: ["10.10.10.177","10.10.10.181"]

but i am getting

hosts: ["10.10.10.177" "10.10.10.181"]

Comma is missing when i substitute the values. Can anyone help to fix above issue.
The difference is due to below

echo [${form_hosts[*]}]
echo "[${form_hosts[*]}]"

Output

["10.10.10.177" "10.10.10.181"]
["10.10.10.177", "10.10.10.181"]

Here under double quotes only comma is coming but i cant use this way inside sed command.

>Solution :

You can do it with Bash’s parameter expansion, no arrays needed:

#!/bin/bash

var_ips="10.10.10.177,10.10.10.181"

sed -i "s/^hosts: \"from_terraform_hosts\"$/hosts: [\"${var_ips//,/\",\"}\"]/g" host.conf

${var_ips//,/\",\"} expands $var_ips but replaces commas with "," and the sed replacement wraps it in [" and "].

Note that this’ll only work as long as $var_ips doesn’t contain any ‘funny stuff’, e.g. spaces (they would end up inside the quotes) or regex-special characters (they would break the sed command).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading