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
總結
到此這篇關于shell腳本如何讀取properties文件中值的文章就介紹到這了,更多相關shell讀取properties文件值內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
linux shell循環:for、while、until用法詳解
這篇文章主要介紹了linux shell下常用的循環for、while、until的用法,這也是腳本之家小編看到的比較詳細的文章了,感興趣的朋友可以參考一下,最好是在環境下自己手工打一份,不要復制2019-04-04
最新評論