Search code examples
bashifs

Bash array from input using ISF


I have a string given in the manner of 1,3, 5, 7-10,... This needs to be put in an array of 1 3 5 7 8 9 10 so anywhere there is a minus sign then I need to add in the missing numbers. I am able to use IFS to split it into an array singling out anyplace there is a comma. The issue is when I use IFS again to split the two numbers such as 7-10, it does not split them. Here is my code:

IFS=', ' read -r -a array <<< "$string"

for index in "${!array[@]}"
do
    if [[ ${array[index]} == *[-]* ]]; then
    IFS='- ' read -r array2 <<< "${array[index]}"
    #for Counter in $(eval echo "{${array2[0]}...${array2[1]}}")
    #do
        #echo "$Counter ${array2[Counter]}"
    echo "0 ${array2[0]}"
    echo "Yes"
    #done
    fi
done

for index in "${!array[@]}"
do
    echo "$index ${array[index]}"
done

And the output from second IFS gives me 7-10 which means it is not splitting it (You can see from the code I was trouble shooting a bit. The idea is to split it and use that in the for loop to append to my existing array the numbers needed.)

If you could point me in the right direction, tell me why this isn't working, or present a better idea that would be great.


Solution

  • Here is a slight update to your code that will work for what you want:

    str="1, 2, 3, 5, 7-10, 11, 12, 15-20, 24"   
    
    IFS=', ' read -r -a arr <<< "$str"
    
    # Empty array, populated in the for-loops below
    array=()          
    
    for elem in ${arr[@]}; do
        if [[ $elem == *[-]* ]]; then
            IFS='-' read -r -a minMax <<< $elem
            for (( j = ${minMax[0]}; j <= ${minMax[1]}; j++ )); do
                array+=($j)
            done
        else
            array+=($elem)
        fi
    done
    
    echo ${array[@]}
    

    which will output:

    1 2 3 5 7 8 9 10 11 12 15 16 17 18 19 20 24