如何使用Shell脚本读取包含带有句点字符的键的.properties文件 [英] How to read a .properties file which contains keys that have a period character using Shell script

查看:307
本文介绍了如何使用Shell脚本读取包含带有句点字符的键的.properties文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从shell脚本中读取属性文件,该文件包含一个句点(.)字符,如下所示:

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.

我的属性文件始终位于脚本的同一目录中或/usr/share/doc中的某个位置

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

推荐答案

由于(Bourne)Shell变量不能包含点,因此可以用下划线替换它们.阅读每一行,翻译. _并进行评估.

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

请注意,以上仅翻译.到_,如果您使用更复杂的格式,则可能需要使用其他翻译.最近,我不得不解析一个包含许多讨厌字符的完整Ant属性文件,在那儿我必须使用:

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_')

这篇关于如何使用Shell脚本读取包含带有句点字符的键的.properties文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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