I need help to split string in bash script with delimiter ',' and ignore spaces in front and back of delimiter.
My string looks like below and ',' is delimiter.
mystring = < hostname1, hostname 2 , hostname value 3 >
Notice that
1. 'hostname1' has extra space in front
2. 'hostname 2' and 'hostname value 3' have extra spaces in front/back
I want to split above string and store in array like below:
mystring[0]:hostname1
mystring[1]:hostname 2
mystring[2]:hostname value 3
Please see below code and output:
HOSTNAME="hostname1 , hostname 2 , hostname value 3 "
IFS=',' read -ra hostnames <<< "$(HOSTNAME)"
for (( i=0; i<=2; i++ ))
do
echo hostname:[${hostnames[i]}]
done
Output
hostname:[hostname1 ]
hostname:[ hostname 2 ]
hostname:[ hostname value 3 ]