0

I used the array assignment below in order to simulate a two dimensional array:

for((i=0;i<2;i++))        
do        
    for((j=0;j<3;j++))        
    do        
        read TWOD$i[$j]        
    done        
done < hi.txt

The file hi.txt contains these lines:

 1    
 2    
 3    
 4     
 5    
 6

If I use echo ${TWOD0[2]}, I can print the value 2, but if I am using a variable for the first index, bash throws a syntax error bad substitution:

 for((i=0;i<2;i++))    
 do    
     printf "%s\n" "${TWOD$i[2]}"    
 done

Is there any way to extract the elements from the array using a variable for the first index?

1

1 Answer 1

2

You can use indirect expansion:

row="TWOD$i[2]"
printf "%s\n" ${!row}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.