Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert multiple lines of one attribute in yaml file with yq v4.x

Tags:

yaml

yq

There is a dynamic attribute stored in input.yaml, I want to insert it into an existed yaml file(named as original.yaml). The attribute has multiple lines.

The two files look like: input.yaml:

- name: bob
  spec: {}

original.yaml:

spec:
    names:
      - name: alice
        spec: {}

My goal is to put input.yaml content under original.yaml spec.names. I tried with yq version 4:

env=$(cat input.yaml)
yq eval '.spec.names + strenv(env)' original.yaml > result.yaml

What I got:

spec:
  names:
    - name: alice
      spec: {}
    - |-
      - name: bob
        spec: {}

there is an unwanted - |- in line 5, I am expected the below output:

spec:
  names:
    - name: alice
      spec: {}
    - name: bob
      spec: {}

Any suggestion will be appreciated.

like image 288
AliceEatFish Avatar asked Dec 06 '25 20:12

AliceEatFish


1 Answers

The idea is right, but you shouldn't be using strenv() function, which formats your input as a YAML string type. Your names record is a an array of maps, so you need to retain the original type, by just using env

So, with that and avoiding cat and using the shell input redirection (should work on bash/zsh/ksh), you could do

item="$(< input.yaml)" yq e '.spec.names += env(item)' original.yaml
like image 59
Inian Avatar answered Dec 10 '25 11:12

Inian