Search code examples
bashshellsplitifs

Split comma separated string by ignoring spaces in front and back of delimiter and store in array in shell script


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 ]

Solution

  • Try the following:

    readarray -t hostnames <<< "$(awk -F, '{ for (i=1;i<=NF;i++) { gsub(/(^[[:space:]]+)|([[:space:]]+$)/,"",$i);print $i } }' <<< "$HOSTNAME")"
    

    Using awk, set the field delimiter to "," and then loop through each field removing spaces from the beginning and end of the strings using gsub, printing the result. The resulting output is then redirected back into readarray to create the hostnames array.