Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I "merge" two YAML text files?

use meld / xxdiff / or something else?

say if I have two yaml files, how can I merge them automatically? each of them has a few hundred lines. the common part is abc:

abc:
  x:
    0: null
  y:
    1: null

def:
  x:
    0: string

...

and

abc:
  u: null
  v: null
  w: null

def:
  u: 
    0: null
  v: null
  w: null
...

desired result:

abc:
  x:
    0: null
  y:
    1: null
  u: null
  v: null
  w: null

def:
  x:
    0: string
  u: 
    0: null
  v: null
  w: null        

can this be done with any diff/merge tools?

edit: fixed typo in desired result

like image 328
Shuman Avatar asked Oct 15 '25 11:10

Shuman


1 Answers

I don't think you can do what you want to without parsing the files. However you can do so with a short python program:

import sys
import ruamel.yaml

yaml = YAML()
yaml.explicit_end = True
data = None

for file_name in sys.argv[1:]:
    d = yaml.load(open(file_name, 'rb'))
    if data is None:
        data = d
        continue
    for k in d:
        data[k].update(d[k])

yaml.dump(data, sys.stdout)

this gives (assuming the appropriate input files:

abc:
  x:
    0:
  y:
    1:     

  u:
  v:
  w:
def:
  x:
    0: string
  u:
    0:
  v:
  w:
...

Please note that the extra whitespace gets lost as ruamel.yaml (disclosure: I am the author of that package), only (partly) preserves whitespace if ajacent to comments. You also would need to make the .update() smarter, i.e. recursive, if more than top-level key merging is required.

like image 90
Anthon Avatar answered Oct 17 '25 02:10

Anthon