shell腳本如何讀取properties文件中的值
如下面代碼所示的properties文件是各種編程語言中常用的屬性文件,通過key讀取value是極其常見的需求。
# 端口 server.port=8520 # 上傳文件總的最大值 spring.servlet.multipart.max-request-size=10MB # 單個文件的最大值 spring.servlet.multipart.max-file-size=10MB
Linux中的shell通常是需要程序員自己寫一個方法實現(xiàn)對properties文件的讀取。以下是我寫的一個方法,親測有效,歡迎各位取用。
#讀取屬性文件指定鍵的值
get_value_of_properties_file() {
result=""
proFilePath="$1"
key="$2"
if [ "WJA${key}" = "WJA" ]; then
echo "參數(shù)錯誤,未能指定有效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
總結
到此這篇關于shell腳本如何讀取properties文件中值的文章就介紹到這了,更多相關shell讀取properties文件值內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
linux 驅動之Kconfig文件和Makefile文件實例
這篇文章主要介紹了linux 驅動之Kconfig文件和Makefile文件實例的相關資料,需要的朋友可以參考下2017-01-01
Shell腳本實現(xiàn)的一個簡易Web服務器例子分享
這篇文章主要介紹了Shell腳本實現(xiàn)的一個簡易Web服務器例子分享,本文實現(xiàn)的Web服務器非常簡單實用,可以在你不想安裝nginx、apache等大型WEB服務器時使用,需要的朋友可以參考下2014-12-12

