【问题标题】:How get variable value from properties file in Shell Script?如何从 Shell 脚本的属性文件中获取变量值?
【发布时间】:2015-05-27 15:56:27
【问题描述】:

我有一个属性文件test.properties,它的内容如下:

x.T1 = 125
y.T2 = 256
z.T3 = 351

如何将 y.T2 (256) 的值分配给 shell 脚本中的某个变量并回显该值?

【问题讨论】:

  • test.properties 的布局是固定的吗?没有空格和点的线条更容易处理。通过简单的配置,您可以使用. test.properties
  • @WalterA : 是的,test.properties 的布局是固定的

标签: shell unix sh


【解决方案1】:

检查一下,会有所帮助:

expVal=`cat test.properties | grep "y.T2" | cut -d'=' -f2`

【讨论】:

    【解决方案2】:

    您想在脚本的循环中使用read。虽然您可以source 一个文件,但如果= 符号周围有空格,则它不起作用。这是处理读取文件的一种方法:

    #!/bin/sh
    
    # test for required input filename
    if [ ! -r "$1" ]; then
        printf "error: insufficient input or file not readable.  Usage: %s property_file\n" "$0"
        exit 1
    fi
    
    # read each line into 3 variables 'name, es, value`
    # (the es is just a junk variable to read the equal sign)
    # test if '$name=y.T2' if so use '$value'
    while read -r name es value; do
        if [ "$name" == "y.T2" ]; then
            myvalue="$value"
        fi
    done < "$1"
    
    printf "\n myvalue = %s\n\n" "$myvalue"
    

    输出

    $ sh read_prop.sh test.properties
    
     myvalue = 256
    

    【讨论】:

    • 感谢您的回复,但= 标志周围有空格。你能根据这个建议答案吗...
    • UUhg... IS 我所做的:p 我知道你只是误读了,买我的答案确实专门处理这种情况。
    • 很高兴我能帮上忙。您几乎可以在 shell 脚本中执行任何您需要的操作。非常值得花时间学习。祝你好运。
    【解决方案3】:

    我知道这是一个老问题,但我只是遇到了这个问题,如果我理解正确,问题是从属性文件中获取特定键的值。 为什么不直接使用 grep 查找键和 awk 获取值?

    使用 grep 和 awk 从 test.properties 中提取值

    export yT2=$(grep -iR "^y.T2" test.properties | awk -F "=" '{print $2}')
    echo y.T2=$yT2
    

    如果 '=' 后面有一个,则该值将包含空格。修剪前导空格

    yT2="${yT2#"${yT2%%[![:space:]]*}"}"
    

    修剪参考: How to trim whitespace from a Bash variable?。 参考链接中提供了解释。

    【讨论】:

      猜你喜欢
      • 2013-03-25
      • 2013-06-15
      • 2018-02-15
      • 2012-01-26
      • 1970-01-01
      • 2016-06-27
      • 2014-03-29
      • 2020-09-05
      • 1970-01-01
      相关资源
      最近更新 更多