使用 Ubuntu 中的 shell 脚本更新 YAML 文件

Update YAML file using shell script in Ubuntu

我必须更新 YAML 文件配置。以下是当前和预期的输出。我怎样才能以更好和最简单的方式使用 shell 脚本来做到这一点?

更新 YAML 文件之前:

# Where and how to store data.
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
#  engine:
#  mmapv1:
#  wiredTiger:

更新 YAML 文件后:

# Where and how to store data.
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
  engine: "wiredTiger"
#  mmapv1:
  wiredTiger:
    engineConfig:
      cacheSizeGB: 4

如果您的输入是 config_in.yaml:

# Where and how to store data.
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true

您可以用 update.py 调用 python update.py wiredTiger 4:

import sys
from pathlib import Path

from ruamel.yaml import YAML

file_name = Path('config_in.yaml')

engine = sys.argv[1]
size = int(sys.argv[2])


yaml = YAML()
data = yaml.load(file_name)
data['storage']['engine'] = engine
data['storage'][engine] = dict(engineConfig=dict(cacheSizeGB=size))
yaml.dump(data, sys.stdout)
yaml.dump(data, Path('config.yaml'))

获取此输出(在标准输出和 config.yaml 中):

# Where and how to store data.
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
  engine: wiredTiger
  wiredTiger:
    engineConfig:
      cacheSizeGB: 4

这假设 Python3(或安装了 pathlib2 的 Python2)和 ruamel.yaml(我是其中的作者)