shell命令获取按键值_如何使用Shell脚本读取包含带有句点字符的键的.properties文件...

I am trying to read a properties file from a shell script which contains a period (.) character like below:

# app.properties

db.uat.user=saple user

db.uat.passwd=secret

#/bin/sh

function pause(){

read -p "$*"

}

file="./app.properties"

if [ -f "$file" ]

then

echo "$file found."

. $file

echo "User Id " $db.uat.user

echo "user password =" $db.uat.passwd

else

echo "$file not found."

fi

I have tried to parse the file after sourcing the file but it is not working since the keys contains the "." character and there are spaces in that value also.

My properties file always resides in the same directory of the script or somewhere in /usr/share/doc

解决方案

As (Bourne) shell variables cannot contain dots you can replace them by underscores. Read every line, translate . in the key to _ and evaluate.

#/bin/sh

file="./app.properties"

if [ -f "$file" ]

then

echo "$file found."

while IFS='=' read -r key value

do

key=$(echo $key | tr '.' '_')

eval ${key}=\${value}

done < "$file"

echo "User Id = " ${db_uat_user}

echo "user password = " ${db_uat_passwd}

else

echo "$file not found."

fi

Note that the above only translates . to _, if you have a more complex format you may want to use additional translations. I recently had to parse a full Ant properties file with lots of nasty characters, and there I had to use:

key=$(echo $key | tr .-/ _ | tr -cd 'A-Za-z0-9_')

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值