如何在Shell脚本中从属性文件中获取变量值?

如何在Shell脚本中从属性文件中获取变量值?,shell,unix,sh,Shell,Unix,Sh,我有一个属性文件test.properties,内容如下: x.T1 = 125 y.T2 = 256 z.T3 = 351 我想读取整个文件,当它找到y.T2时,它应该将它的值赋给shell脚本中的某个变量,并回显该值 我不熟悉shell脚本。请帮助我并提前感谢您想在脚本中循环使用阅读。虽然您可以源文件文件,但是如果=符号周围有空格它就不起作用。以下是处理读取文件的方法: #!/bin/sh # test for required input filename if [ ! -r "$1"

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

x.T1 = 125
y.T2 = 256
z.T3 = 351
我想读取整个文件,当它找到
y.T2
时,它应该将它的值赋给shell脚本中的某个变量,并回显该值


我不熟悉shell脚本。请帮助我并提前感谢

您想在脚本中循环使用
阅读
。虽然您可以
源文件
文件,但是如果
=
符号周围有空格
它就不起作用。以下是处理读取文件的方法:

#!/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"

我知道这是一个老问题,但我刚刚遇到了这个问题,如果我理解正确,问题是从属性文件中获取特定键的值。 为什么不直接使用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:]]*}"}"
修剪参考: .
参考链接提供解释。

检查此项,将准确帮助:

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

test.properties的布局是否已修复?没有空格和点的线更容易处理。通过一个简单的配置,您可以使用
。test.properties
@WalterA:是的,
test.properties
的布局是固定的,感谢您的响应,但是
=
符号周围有空格。你能根据…UUhg…建议答案吗。。。这就是我所做的
:p
我知道你只是误读了,我的答案确实处理了这个问题。很高兴我能帮上忙。在shell脚本中,几乎可以执行任何需要的操作。值得花时间学习。祝你好运
expVal=`cat test.properties | grep "y.T2" | cut -d'=' -f2`