SED:在.yml文件中的环境特性变化值 [英] sed: change values of properties of an environment in a .yml file

查看:481
本文介绍了SED:在.yml文件中的环境特性变化值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个配置应用程序的环境属性,比如像这样的.yml文件:

I have an .yml file that configures environment properties of an application, such like this:

env1:
  :prop1: "value1"
  :prop2: "value2"
        ...
  :propn: "valuen"

env2:
  :prop1: "value1"
  :prop2: "value2"
  :prop3: "value3"
        ...
  :propn: "valuen"

    ...

envn:
  :prop1: "value1"
  :prop2: "value2"
        ...
  :propn: "valuen"

我想产生一个bash脚本如下界面:

I would like to produce a bash script with the following interface:

$ change_env.sh <environment> <property> <new value> <file.yml>

例如:

$ change_env.sh env2 prop3 "this value was changed" file.yml

的输出将是:

env1:
  :prop1: "value1"
  :prop2: "value2"
        ...
  :propn: "valuen"

env2:
  :prop1: "value1"
  :prop2: "value2"
  :prop3: "this value was changed"
        ...
  :propn: "valuen"

    ...

envn:
  :prop1: "value1"
  :prop2: "value2"
        ...
  :propn: "valuen"

我发现这个职位,但是我不能这样做,我的情况工作。
<一href=\"http://stackoverflow.com/questions/1348124/replace-an-xml-elements-value-sed-regular-ex$p$pssion\">Replace XML元素的价值?桑达定期EX pression?

我也试过这样:(它失败,因为变造的所有属性)

I also tried this: (it fails because alters all properties)

sed 's/\(:pro3:\).*/\1 "new value"/'

在此先感谢!
- 洛伦索

Thanks in advance! -- Lourenco.

推荐答案

(很漂亮的第一篇文章!)

(very nice first post!)

试试这个

cat change_env.sh

#!/bin/bash
# spec : change_env.sh <environment> <property> <new value> <file.yml>

case ${#} in [!4] ) 
    print "usage: change_env.sh <environment> <property> <new value> <file.yml>" 
    exit 1 
   ;; 
esac

env="$1" prop="$2" new="$3" file="$4"
bakFile="${file}".bak
mv "$file" "$bakFile"
sed '/^'"${env}"'/,/^[   ]*$/{  # [ spaceChar tabChar ]
         /'"${prop}"'/s//'"${new}"'/p
    }' "$bakFile" > "$file"

修改

请注意,如果你希望输入到包含的值的空白,你会想要修改脚本引用的所有变量($ 1,$ 2...)。 (我现在已经做到了这一点,因为它是一个shell脚本最佳实践)。

Note, if you expect input to contain white-space in the values you'll want to modify script to quote all variables ("$1","$2"...). (I have now done this, as it is a shell-scripting best practice).

/ env的/,/ ^ [{空格,制表}] * $ / 是一个范围的地址sed的。它读取包含您的环境设置的文本块。我假设你的样品输入是正确的,并且每个ENV由空行分隔。嗯...这将包括在文件中的最后一个。
(测试掉以轻心,必须到现在吃饭; - )

The /env/,/^[{space,tab}]*$/ is a range address for sed. It reads a block of text that contains your environment settings. I'm assuming your sample input is correct and that each env is separated by a blank line. Hmm... this would include the last one in the file. (lightly tested, have to go to dinner now ;-)

IHTH

这篇关于SED:在.yml文件中的环境特性变化值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆