Search code examples
yamlyq

YQ edit files with multiple document in place


I have a YAML file with 2 documents

# template.yaml

a : 1
---
b : 2

I'm trying to edit the YAML file inplace. I've tried using

# yq4

yq -i '
    select(documentIndex == 0) | 
    .a = 3 |
    select(documentIndex == 1) |
    .b = 4
' template.yaml

But figured out that this outputs an empty file. I figured that the output of select(documentIndex == 0) | .a = 3 is a single document, which when piped to select(documentIndex == 1), results in an empty document.

In yq3, I can do this by writing

#yq3

yq w -d1 .a 3 | yq w -d2 .b 4` > template.yaml

Is there an equivalent to this yq4 command in yq3?


Solution

  • You have it right, on why it doesn't work with mikefarah/yq v4. A simpler way to do that would be to do

    yq 'select(di == 0).a  = 3  | select(di == 1).b = 5'  yaml
    

    It is not recommended to use the in-place substitution flag, before verifying the contents of the stdout. Always add it afterwards.