自己写小工具需要用到shell读写ini文件,在网上找了很多资料,自己整理的目前使用没问题的代码如下:
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() { # 函数使用说明: # write_ini_file <文件> <节> <键> <值> # 如果节或者键不存在,则添加 # 如果节、键存在,值不匹配,则更新 # 如果节、键、值均存在,则不做操作 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 # 如果替换失败,可能文件中有\,更换分隔符为! if [[ "$?" -ne 0 ]];then sed -i "${itemnum},/^\[.*\]/s!\($3.\?=\).*!\1$4!g" $1 fi else # 新增 sed -i "/^\[$2\]/a\\$3=$4" $1 fi } # 判断输入参数 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} } # 判断输入参数 get_opt $file $section $key
到此这篇关于使用shell实现ini文件的读写的文章就介绍到这了,更多相关shell读写ini文件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论