Search code examples
yamlyq

Parse Yaml with sentence or multiple words


I have a yaml file -

groups:
  - name: Group 1 for Application 1
  - name: Group 2 for Application 2

I need to parse this yaml, and store it in a variable so that I can iterate.

If I just do

group_names=($(yq eval '.groups[].name' test.yaml))
for name in "${group_names[@]}"; do
    echo $name
done

It prints

Group
1
for
Application
1
Group
2
for
Application
2

I also tried

group_names=($(yq eval '.groups[].name | join(",")' test.yaml))
Error: cannot join with !!str, can only join arrays of scalars

Solution

  • If you want to store every .name value from the YAML array .groups into an indexed Bash array group_names, use Bash's declare -a to define an array, and yq's @sh to escape the values for shell. Wrap the declaration in parentheses to make it an array, and use double quotes in Bash to print values that contain whitespace characters.

    unset group_names
    declare -a group_names="($(yq eval '.groups[].name | @sh' test.yaml))"
    
    for name in "${group_names[@]}"; do echo "Next name: $name"; done
    
    Next name: Group 1 for Application 1
    Next name: Group 2 for Application 2
    

    Tested with mikefarah/yq version v4.35.1 (Note: since version 4.18.1, the eval command can be omitted)

    For kislyuk/yq, replace yq eval with yq -r.