0

If I have a variable like:

var="123456677
123456677
123456677
123456677
123456677"

i want to convert it to an array such as

a[0]='1'
a[1]='2'
a[2]='3'
a[3]='4'
  .
  .
  .
a[n-4]='6'
a[n-3]='6'
a[n-2]='7'
a[n-1]='7'

how can I do that in bash?

  • edited. I want it as an array of elements, first line elements should be stored in first line of array, second to second row, so on.. – Ancy David Apr 22 '21 at 21:10
  • 1
    Do you really mean to have all the leading spaces that need to be stripped out? – Charles Duffy Apr 22 '21 at 21:10
  • 1
    Also, if you run `a[0]='1'; a[0]='2'; a[0]='3'; a[0]='4'`, you get only a `4` -- the other items are overwritten. – Charles Duffy Apr 22 '21 at 21:11
  • yes if it makes confusion I will edit it – Ancy David Apr 22 '21 at 21:11
  • Very, _very_ short answer (which is duplicative of existing knowledgebase contents): `readarray -t a <<<"$str"` for bash 4.0+, `IFS=$'\n' read -r -d '' -a a <<<"$str"` -- if you want to split _by lines_. If you want to index in character-by-character, it makes more sense to just leave it as a string. – Charles Duffy Apr 22 '21 at 21:11
  • `"${str:idx:1}` will retrieve one character from position `idx` in a string; why bother with making it an array at all, if you're going character-by-character? – Charles Duffy Apr 22 '21 at 21:14
  • actually I am trying to solve a maze and I want to convert maze output to an array to check if has a path from start to end – Ancy David Apr 22 '21 at 21:16
  • I'm not sure I understand what converting it into an array has to do with checking for existence of a path. – Charles Duffy Apr 22 '21 at 21:17
  • to check the positions above left right and below? to know if its empty or not? I'm new to this I have no idea I am trying with basic logic – Ancy David Apr 22 '21 at 21:19
  • Still not sure how being an array helps you with that. Bash arrays are one-dimensional -- you only have `arr[idx]`, not `arr[x][y]`. And if you have `arr[idx]`, well, it's _exactly the same thing_ as `${str:idx:1}`. – Charles Duffy Apr 22 '21 at 21:22
  • Sure, you can convert from `x` and `y` to `idx` with some easy math, but that `idx` once you have it is used the same way in both array and string cases. For that matter, in C, `arr[x][y]` is really just syntactic sugar for `arr[(x*width)+y]`, and you can do that same `x*width+y` logic without needing the language to provide syntactic sugar for you at all. – Charles Duffy Apr 22 '21 at 21:23

0 Answers0