1

I have an array of strings with the following numbers in it separated by a space.

S0 [
42 4677
S10 [
4719 1266
6020 3618
9667 8463

I want to separate each value as an integer and put the in a separate array like array2 = [S0,42, 4677,S10, 4719, 1266, 6020, 3618, 9667, 843].

What I have done is loop through the array like the solution given here

How to split one string into multiple strings separated by at least one space in bash shell?

for each element of the array but it doesn't seem to work.

for each in ${my_array[1]}
do
echo $each
done

always gives me the output 42 4677 as a single value.

EDITED

for each in ${my_array[@]}
do
echo $each 
done    

declare -a array2
for each in ${my_array[@]}
do
    array2=$each
done 

echo ${array2[1]}

declare -p my_array 

Now the first for loop works correctly but now when I assign the values of my_array to array2 in the second loop, only the last value of the last string is assigned to it i.e. 8463.

The contents of declare -p my_array are declare -a my_array='([0]="S0 [" [1]="42 4677" [2]="S10 [" [3]="4719 1266" [4]="6020 3618" [5]="9667 8463")'

Saad
  • 159
  • 1
  • 2
  • 14

1 Answers1

1

You can use:

declare -a my_array='([0]="S0 [" [1]="42 4677" [2]="S10 [" [3]="4719 1266" [4]="6020 3618" [5]="9667 8463")'

array2=()

for i in ${my_array[@]}; do
   [[ $i == *[0-9]* ]] && array2+=($i)
done

# check content of array2
declare -p array2
declare -a array2=([0]="S0" [1]="42" [2]="4677" [3]="S10" [4]="4719" [5]="1266" [6]="6020" [7]="3618" [8]="9667" [9]="8463")
anubhava
  • 761,203
  • 64
  • 569
  • 643