当前位置: 代码网 > 服务器>服务器>Linux > 使用Shell实现ini文件的读写

使用Shell实现ini文件的读写

2025年02月13日 Linux 我要评论
自己写小工具需要用到shell读写ini文件,在网上找了很多资料,自己整理的目前使用没问题的代码如下:set代码:#!/bin/bash # 提示信息msg="please input the par

自己写小工具需要用到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文件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com