unix Yaml -如何使用sed替换键值?

2j4z5cfb  于 2023-01-05  发布在  Unix
关注(0)|答案(2)|浏览(316)

我有一个yaml配置,我想用一个新值替换其中一个字段?
下面是一个yaml配置的例子:

application: "app_name"
pipeline: "app-pipeline"
parameters:
  spinnaker_environment: "production"
  perform_cleanup: false
  build_image_tag: "foobar"

我想把build_image_tag字段下的"foobar"替换成一个不同的值,比如"latest",我该怎么做?
我尝试了以下方法:

sed '/^parameters:/{n;s/build_image_tag:.*/build_image_tag: "latest"/;}' exec.yml

但这似乎并不起作用,yaml的配置应该是这样的:

application: "app_name"
pipeline: "app-pipeline"
parameters:
  spinnaker_environment: "production"
  perform_cleanup: false
  build_image_tag: "latest"
zmeyuzjn

zmeyuzjn1#

对于go yqpython yq,正确的工具:

$ yq -i '.parameters.build_image_tag="latest"' file.yaml
application: "app_name"
pipeline: "app-pipeline"
parameters:
  spinnaker_environment: "production"
  perform_cleanup: false
  build_image_tag: "latest"
  • 对于JSONyq使用与jq相同的语法
  • -ised -i相同:动态替换
mkh04yzy

mkh04yzy2#

sed中有一个“S”命令,其工作原理如下:

# sed 's/pattern/replacement/[g]' - g is an optional flag to replace all instances

# examples:
echo "a b b c" | sed 's/b/d/'
a d b c

echo "a b b c" | sed 's/b/d/g'
a d d c

对于您的示例,它将是这样的:

sed 's/foobar/latest/' exec.yml

我建议创建一个模板文件,如下所示:

cat template.yml
application: "_APP_"
pipeline: "_PIP_"
parameters:
  spinnaker_environment: "_ENV_"
  perform_cleanup: _CLN_
  build_image_tag: "_IMG_"

然后用sed来修改它,如下所示:

sed '
  s/_APP_/app_name/;
  s/_PIP_/app-pipeline/;
  s/_ENV_/production/;
  s/_CLN_/false/;
  s/_IMG_/latest/;
' template.yml > new.yml

使用变量:

app=app_name
pip=app-pipeline
env=production
cln=false
img=latest

sed "
  s/_APP_/$app/;
  s/_PIP_/$pip/;
  s/_ENV_/$env/;
  s/_CLN_/$cln/;
  s/_IMG_/$img/;
" template.yml > new.yml

相关问题