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

Mongodb 在Ubuntu中使用shell脚本更新YAML文件,mongodb,shell,yaml,ubuntu-16.04,Mongodb,Shell,Yaml,Ubuntu 16.04,我必须更新YAML文件配置。以下是当前和预期输出。如何以更好、最简单的方式使用shell脚本 在更新YAML文件之前: # Where and how to store data. storage: dbPath: /var/lib/mongodb journal: enabled: true # engine: # mmapv1: # wiredTiger: # Where and how to store data. storage: dbPath: /var/l

我必须更新YAML文件配置。以下是当前和预期输出。如何以更好、最简单的方式使用shell脚本

在更新YAML文件之前:

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

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

如果您的输入位于.yaml中的
配置中

# Where and how to store data.
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
# Where and how to store data.
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
  engine: wiredTiger
  wiredTiger:
    engineConfig:
      cacheSizeGB: 4
您可以使用
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
中):


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

您应该始终使用解析器来进行此类更新,使用一个shell脚本(调用
sed
awk
),该脚本不知道yaml的内部结构,但一定会在某个时刻中断。(关于引号、折线、注释、块与流样式等)与@Anthon非常一致。我的意思是“只是文字”,所以你可以做任何你想做的事。但它实际上是一个“序列化的数据结构”,因此,根据您的需求解析和修改数据结构,然后将其再次输出为YAML,这是非常有意义的。它几乎已经过时了,因为即使CSV也可以非常简单,但打破它也非常简单。数据结构通常最好留给理解它们的事物。IHMO,作为旁注,您的“编辑”非常通用。因此,似乎没有任何理由不能简单地将现有配置换成新配置。当然,除非问题中没有提到某些特定于实例的数据,@Anthon在我的场景中使用它的最佳解析器是什么?因为您的YAML中有注释,我推荐ruamel.YAML(我是该Python包的作者)。这是我所知道的唯一一个试图保留注释和键顺序的解析器。您可以将大小作为命令行参数传递,Pythonengine的长度不应超过10-15行:“wiredTiger”在输出中丢失。我也不想要这句话。这是我在执行脚本后的输出在何处以及如何存储数据。storage:dbPath:/var/lib/mongodb journal:enabled:true wiredTiger:engineConfig:cacheSizeGB:4 35; engine:#mmapv1:#wiredTiger:I更新了脚本。删除评论是可能的,但不像在我的输入中那样容易。特别是因为假设多个注释行是一个注释块。