1

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.

Josh
  • 159
  • 2
  • 10

2 Answers2

0

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
assefamaru
  • 2,751
  • 2
  • 10
  • 14
  • I copied your exact code, which looks sound to me and I'm still getting the same problem that it is not splitting them. The error is ((: j = 7 10: syntax error in expression (error token is "10") If I echo minMax[0] I get 7 10[0] – Josh Apr 17 '18 at 14:39
  • @Josh, try quoting `$elem` in `IFS='-' read -r -a minMax <<< $elem` so that it becomes `IFS='-' read -r -a minMax <<< "$elem"`. – assefamaru Apr 18 '18 at 02:57
0

Without using a loop,

string="1,3, 5, 7-10"
string=$(echo "$string" | sed -e 's/\(\([0-9]\+\)-\([0-9]\+\)\)/{\2..\3}/g' | sed -e 's/,/ /g')
eval declare -a array=("$string")
echo ${array[*]}

which yields

1 3 5 7 8 9 10
tshiono
  • 21,248
  • 2
  • 14
  • 22