Home > Enterprise >  Replace list of data from one file YAML to another file preserving the format(indentation)
Replace list of data from one file YAML to another file preserving the format(indentation)

Time:09-27

I have a below YAML file called file1.yaml

default:
  app:
    service-v1:
      country:
        list: LIST_TO_REPLACE 

I am trying to replace LIST_TO_REPLACE text with the below YAML file list data.

file2.yml

app:
  list-data: // Need to extract this node data and replace in the file1.yml
    - key1: value
      key2: value
      key3: 
        - list1
        - list2
        - list3
    - key4: value
      key5: value
      key6: 
        - list1
        - list2
        - list3

I am using YQ to replace the list of data from file2 to file1. But it is not correctly indented in file1.

Is there any way to replace the entire node and it could follow the indentation of file1?

Expected Output:

default:
  app:
    service-v1:
      country:
        list: //After replace operation
          - key1: value
            key2: value
            key3: 
          - list1
          - list2
          - list3
          - key4: value
            key5: value
            key6: 
          - list1
          - list2
          - list3 

CodePudding user response:

As you have tagged jq, I assume you are looking for a solution using kislyuk/yq. Here's one using input for the second file:

yq -y '
  .default.app."service-v1".country.list = input.app."list-data"
' file1.yaml file2.yaml
default:
  app:
    service-v1:
      country:
        list:
          - key1: value
            key2: value
            key3:
              - list1
              - list2
              - list3
          - key4: value
            key5: value
            key6:
              - list1
              - list2
              - list3

For a solution using mikefarah/yq, you could use load to read the second file.

yq '
  .default.app."service-v1".country.list = load("file2.yaml").app."list-data"
' file1.yaml
default:
  app:
    service-v1:
      country:
        list:
          - key1: value
            key2: value
            key3:
              - list1
              - list2
              - list3
          - key4: value
            key5: value
            key6:
              - list1
              - list2
              - list3

Note: With this implementation of yq, you can also use the -i flag to modify file1.yaml in-place.

  • Related