Search code examples
bashshellcommand-lineyamlyq

How to index a yaml file using yq with "---" separater


Here is a sample yaml file to explain the issue:

hello: null
---
hello: null

There are two keys with the same name in a yaml file separated by "---". Both need different values.

I am using yq in a bash script to set the values of certain keys. I am currently using this command for a yaml file without the "---" separater and it works:

yq -i -y ".hello=\"world\"" ./$PATH

But when I try and index one of the keys in a file with "---" using:

yq -i -y ".[0].hello=\"world\"" ./$PATH

I get this error:

jq: error (at <stdin>:1): Cannot index object with number
jq: error (at <stdin>:2): Cannot index object with number

I'm sure the syntax is incorrect but I can't seem to get it to work or find any documentation on this specific problem I'm facing.


Solution

  • Please specify which implementation of yq you are using.

    For mikefarah/yq, you can use document_index (or di) to reference into a specific document:

    yq 'select(document_index == 0).hello = "world"'
    # or
    yq 'select(di == 0).hello = "world"'
    

    For kislyuk/yq, you can use the --slurp (or -s) flag to collect the documents into an array which you can then index into, then iterate over the items to re-generate the multi-document output:

    yq --slurp -y '.[0].hello = "world" | .[]'
    # or
    yq -sy '.[0].hello = "world" | .[]'
    

    Both examples output:

    hello: world
    ---
    hello: null