在shell脚本中如何读取properties文件中的值

如下面代码所示的properties文件是各种编程语言中常用的属性文件,通过key读取value是极其常见的需求。

# 端口
server.port=8520
# 上传文件总的最大值
spring.servlet.multipart.max-request-size=10MB
# 单个文件的最大值
spring.servlet.multipart.max-file-size=10MB

Linux中的shell通常是需要程序员自己写一个方法实现对properties文件的读取。以下是我写的一个方法,亲测有效,欢迎各位取用。

#读取属性文件指定键的值
get_value_of_properties_file() {
  result=""
  proFilePath="$1"
  key="$2"
    if [ "WJA${key}" = "WJA" ]; then
    echo "参数错误,未能指定有效Key。"
    echo "" >&2
    exit 1
  fi
  if [ ! -f ${proFilePath} ]; then
    echo "属性文件(${proFilePath})不存在。"
    echo "" >&2
    exit 1
  fi
  if [ ! -r ${proFilePath} ]; then
    echo "当前用户不具有对属性文件(${proFilePath})的可读权限。"
    echo "" >&2
    exit 1
  fi
  keyLength=$(echo ${key}|wc -L)
  lineNumStr=$(cat ${proFilePath} | wc -l)
  lineNum=$((${lineNumStr}))
  for ((i = 1; i <= ${lineNum}; i++)); do
    oneLine=$(sed -n ${i}p ${proFilePath})
    if [ "${oneLine:0:((keyLength))}" = "${key}" ] && [ "${oneLine:$((keyLength)):1}" = "=" ]; then
      result=${oneLine#*=}
      break
    fi
  done
  echo ${result}
}

使用示例: 方法名 properties文件路径 key 。如get_value_of_properties_file /home/wja/test.properties server.port

评论 29
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民工老王

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值