0

I have a read the output of a function into a variable.

The data looks like this

---
data:
  pkg:
    -
      NAME: 'bob'
      FEATURE: Big
    -
      NAME: 'sue'
      FEATURE: Tall
    -
      NAME: 'jim'
      FEATURE: Slim

I see examples of iterating over an array. Those examples always create the array by hand.

Is there a way to transform the hash into an array? How do I do that? Or can I deal with it in this form?

I'd like to echo the FEATURE of each pkg.

jimlongo
  • 365
  • 2
  • 5
  • 21
  • 1
    You haven't seen examples like `arrayName[$key]=$value` to create array elements dynamically? – Barmar Apr 11 '19 at 20:38
  • 1
    Why do you think you need a multidimensional array? Bash doesn't have them. – Barmar Apr 11 '19 at 20:39
  • Well, if you really need the data structure in bash, you must "simulate" multidimensional array. If I need to `echo` all values of some dictionary key from a YML, I would do this with `grep` and `sed`. – Aurium Apr 11 '19 at 21:06
  • 1
    You should switch to a language with a real YAML parser; `grep` and `sed` are not sufficient. – chepner Apr 11 '19 at 21:32
  • This would probably be trivial to do using [yq](https://yq.readthedocs.io/en/latest/). – Shawn Apr 12 '19 at 03:56

1 Answers1

0

The yaml in your example represents an array of dictionaries. Bash doesn't do multidimensional arrays of any sort.

You can, however, simulate the result by parsing your data into parallel arrays, so that ${name[0]} of bob corresponds by its zero index with ${feature[0]} of Big.

The real problem is manually parsing YAML, which I don't recommend.

If you really need to dive into that, check out this discussion which has some options.

Paul Hodges
  • 13,382
  • 1
  • 17
  • 36