'Using yq to traverse a list in Almquist shell
I have this example of a YAML file, which includes a variable number of elements in the 'containers' list and in the 'networks' list of each container.
lab_name: practica0
containers:
- name: vm1
image: rys
networks:
- 1
- name: router
image: rys
networks:
- 1
- 2
- name: vm2
image: rys
networks:
- 2
I wanna loop through the 'containers' and the 'networks' arrays getting all the values, but I don't know exactly how to do it. I tried using a for loop and a shell variable, like this yq eval '.containers[$i].name' example.yaml, but it didn't work. I tried enclosing $i between double quotes and escaping them as specified here https://github.com/mikefarah/yq/issues/468#issuecomment-752114840, but still no luck. I'm using Go yq by the way, and I have to use Almquist Shell instead of bash so I can't use things like readarray. Thank you
EDIT: For example, my desired output would be something as simple as this:
vm1
rys
1
router
rys
1
2
vm2
rys
2
Solution 1:[1]
You can use something like
yq e '.containers | map([ .name, .image, .networks[] ])' input
to create a list of values you desire:
- - vm1
- rys
- 1
- - router
- rys
- 1
- 2
- - vm2
- rys
- 2
Not sure what the prevered way is to convert this into a new-line separated string. But with some additional logic, we can get the desired output using the sed and tr utilities.
Use @tsv to let yq create a tab separated value, then we use some common shell utilities to convert that to the desired output
sed Gplaces a newline after each linetr '\t' '\n'replaces the tab with an other newline
yq e '.containers | map([ .name, .image, .networks[] ]) | @tsv' input | sed G | tr '\t' '\n'
vm1
rys
1
router
rys
1
2
vm2
rys
2
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | 0stone0 |
