0

I want to ask about the syntax i use to assign a value of a two dimensional array element to a variable. this is basically what i am trying to do: I have a 2 dimensional array of characters and a string called sub_string that gets the value of a particular element in the array and put it in another string called whole_string

for ((j=1;j<=num_columns;j++)) do
      for ((i=1;i<=num_rows;i++)) do

Assigning the value of the element [i,j] in the array matrix to a sub string

    whole_string="$whole_String$sub_string"
    done
done

I want to know how to assign the value of the array to the sub string i have. thank you

4
  • 1
    bash does not have two-dimensional arrays, nor can you store an array inside another array. Commented Aug 31, 2014 at 18:58
  • ...well, one can escape an array -- as in printf -v arr_str '%q ' "${arr[@]}" -- and store the resulting string as an array element... but still the question is far, far too vague and unclear to understand whether this would actually be in furtherance of a reasonable goal. Commented Aug 31, 2014 at 19:01
  • A one-dimensional associative array with keys of the form ${x}_$y is sometimes good enough to simulate a two-dimensional array... but again, question much too unclear. Commented Aug 31, 2014 at 19:01
  • Sure, there are lots of way to fake it, but it's debatable whether any are worth the effort. If you need such a data structure, bash (or any shell I can think of) is the wrong choice. Commented Aug 31, 2014 at 19:03

1 Answer 1

3

With a current bash you can divert an associative array to create multidimensional arrays.

#!/bin/bash

declare -A A    # declare associative array A
num_rows=7
num_columns=9

# fill array
for ((j=1;j<=num_rows;j++)) do
  for ((i=1;i<=num_columns;i++)) do
    A[$j,$i]="$j:$i"   # fill with row:column
  done
done

# print array
for ((j=1;j<=num_rows;j++)) do
  for ((i=1;i<=num_columns;i++)) do
    echo -n "${A[$j,$i]} "
  done
  echo
done

Output (9x7 array):

1:1 1:2 1:3 1:4 1:5 1:6 1:7 1:8 1:9 
2:1 2:2 2:3 2:4 2:5 2:6 2:7 2:8 2:9 
3:1 3:2 3:3 3:4 3:5 3:6 3:7 3:8 3:9 
4:1 4:2 4:3 4:4 4:5 4:6 4:7 4:8 4:9 
5:1 5:2 5:3 5:4 5:5 5:6 5:7 5:8 5:9 
6:1 6:2 6:3 6:4 6:5 6:6 6:7 6:8 6:9 
7:1 7:2 7:3 7:4 7:5 7:6 7:7 7:8 7:9 
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.