使用Shell實現(xiàn)ini文件的讀寫
更新時間:2024年11月30日 11:42:20 作者:Lydro
這篇文章主要為大家詳細(xì)介紹了如何使用Shell實現(xiàn)ini文件的讀寫,文中的示例代碼簡潔易懂,具有一定的借鑒價值,有需要的小伙伴可以參考一下
自己寫小工具需要用到shell讀寫ini文件,在網(wǎng)上找了很多資料,自己整理的目前使用沒問題的代碼如下:
set代碼:
#!/bin/bash # 提示信息 msg="Please input the param 【<get|set> <file> <section> <key> [value]】" # 操作文件 file=$1 # 指定section section=$2 # 指定key key=$3 # value value=$4 function get_opt() { INIFILE=$1; SECTION=$2; ITEM=$3 tmpfile="/tmp/tmp.ini" # 去掉配置文件中的注釋行和空行,保存到tmpfile中。 sed '/^#/d;/^$/d' ${INIFILE} > ${tmpfile} _readIni=`awk -F '=' '/\['${SECTION}'\]/{a=1}a==1&&$1~/'${ITEM}'/{print $2;exit}' ${tmpfile}` echo ${_readIni} } function set_opt() { # 函數(shù)使用說明: # write_ini_file <文件> <節(jié)> <鍵> <值> # 如果節(jié)或者鍵不存在,則添加 # 如果節(jié)、鍵存在,值不匹配,則更新 # 如果節(jié)、鍵、值均存在,則不做操作 allSections=$(awk -F '[][]' '/\[.*]/{print $2}' $1) iniSections=(${allSections// /}) # 判斷是否要新建item itemFlag="0" for temp in ${iniSections[@]};do if [[ "${temp}" = "$2" ]];then itemFlag="1" break fi done if [[ "$itemFlag" = "0" ]];then echo "[$2]" >> $1 fi # 加入或更新value awk "/\[$2\]/{a=1}a==1" $1|sed -e '1d' -e '/^$/d' -e 's/[ \t]*$//g' -e 's/^[ \t]*//g' -e '/\[/,$d'|grep "$3.\?=">/dev/null if [[ "$?" -eq 0 ]];then # 更新 # 找到指定item行號碼 itemNum=$(sed -n -e "/\[$2\]/=" $1) sed -i "${itemNum},/^\[.*\]/s/\($3.\?=\).*/\1$4/g" $1 >/dev/null 2>&1 # 如果替換失敗,可能文件中有\(zhòng),更換分隔符為! if [[ "$?" -ne 0 ]];then sed -i "${itemNum},/^\[.*\]/s!\($3.\?=\).*!\1$4!g" $1 fi else # 新增 sed -i "/^\[$2\]/a\\$3=$4" $1 fi } # 判斷輸入?yún)?shù) set_opt $file $section $key $value
get代碼:
#!/bin/bash # 提示信息 msg="Please input the param 【<get|set> <file> <section> <key> [value]】" # 操作文件 file=$1 # 指定section section=$2 # 指定key key=$3 function get_opt() { INIFILE=$1; SECTION=$2; ITEM=$3 tmpfile="/tmp/tmp.ini" # 去掉配置文件中的注釋行和空行,保存到tmpfile中。 sed '/^#/d;/^$/d' ${INIFILE} > ${tmpfile} _readIni=`awk -F '=' '/\['${SECTION}'\]/{a=1}a==1&&$1~/'${ITEM}'/{print $2;exit}' ${tmpfile}` echo ${_readIni} } # 判斷輸入?yún)?shù) get_opt $file $section $key
到此這篇關(guān)于使用Shell實現(xiàn)ini文件的讀寫的文章就介紹到這了,更多相關(guān)Shell讀寫ini文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
shell 生成隨機數(shù)的實現(xiàn)方法總結(jié)
這篇文章主要介紹了 shell 生成隨機數(shù)的實現(xiàn)方法總結(jié)的相關(guān)資料,希望通過本能幫助到大家,讓大家徹底掌握這幾種隨機數(shù)的方法,需要的朋友可以參考下2017-09-09Linux下查看.so和可執(zhí)行文件是否debug編譯的方法(必看)
下面小編就為大家?guī)硪黄狶inux下查看.so和可執(zhí)行文件是否debug編譯的方法(必看)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-03-03詳解linux下利用crontab創(chuàng)建定時任務(wù)
這篇文章主要介紹了linux下利用crontab創(chuàng)建定時任務(wù)的相關(guān)資料,需要的朋友可以參考下2017-04-04Linux命令dos2unix命令示例詳解(將DOS格式文本文件轉(zhuǎn)換成Unix格式)
dos2unix命令 用來將DOS格式的文本文件轉(zhuǎn)換成UNIX格式的,而Unix格式的文本文件在Windows下用Notepad打開時會拼在一起顯示,本文介紹Linux命令dos2unix命令示例詳解(將DOS格式文本文件轉(zhuǎn)換成Unix格式),感興趣的朋友一起看看吧2024-04-04