我必须更新 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.pywiredTiger 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'))
获取此输出(在 stdout 以及 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(我是作者)
关于mongodb - 在 Ubuntu 中使用 shell 脚本更新 YAML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46190396/