比较两个 yaml 文件并根据键从第一个文件中获取匹配的元素

Compare two yaml file and get matching elements from first file based on key

我正在尝试比较这两个 YAML 文件,如果这两个文件之间的键匹配,我会尝试从第一个文件中提取键值对。查看预期输出以获得更清晰的信息。

YAML 文件 1:

  COMMON-VAR: "[\n  { \"DESC\": \"A\", \"O\": \"h\", \"confidence\":0.8 },\n  { \"DESC\": \"B\", \"O\": \"u\", \"C\":0.8 }\n { \"DESC\": \"A\", \"O\": \"h\", \"confidence\":0.8 },\n "
  LASTNAME: "D"
  FIRSTNAME: "JOHN"
  UNKNOWN: "!!"

YAML 文件 2:

  COMMON-VAR: "[\n  { \"DESC\": \"A\", \"O\": \"h\", \"confidence\":0.8 },\n  { \"DESC\": \"B\", \"O\": \"u\", \"C\":0.8 }\n"
  LASTNAME: "E"
  FIRSTNAME: "JOHN"
  ADDRESS: "SanJose, CA"
  ZIP: "09817"

预期输出:

  COMMON-VAR: "[\n  { \"DESC\": \"A\", \"O\": \"h\", \"confidence\":0.8 },\n  { \"DESC\": \"B\", \"O\": \"u\", \"C\":0.8 }\n { \"DESC\": \"A\", \"O\": \"h\", \"confidence\":0.8 },\n "
  LASTNAME: "D"

我的尝试:

join <(sort file1.yaml) <(sort file2.yaml) | awk '!={print ,}' | yq e -I4

当我的值中没有花括号时它可以工作,但是当我在 yaml 文件中的值中有 {}awk 失败。

一个awk想法:

awk -F':' '
FNR==NR                    { seen[]=[=10=]; next }
 in seen && [=10=]!=seen[] { print seen[] }
' file1.yaml file2.yaml

或者,如果文件以相反的顺序输入,则输入的次数会稍微少一些:

awk -F':' '
FNR==NR                    { seen[]=[=11=]; next }
 in seen && [=11=]!=seen[]
' file2.yaml file1.yaml

这两个生成:

  COMMON-VAR: "[\n  { \"DESC\": \"A\", \"O\": \"h\", \"confidence\":0.8 },\n  { \"DESC\": \"B\", \"O\": \"u\", \"C\":0.8 }\n { \"DESC\": \"A\", \"O\": \"h\", \"confidence\":0.8 },\n "
  LASTNAME: "D"