shell读取config.ini文件

2021/8/19 7:07:27

本文主要是介绍shell读取config.ini文件,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

shell读取config.ini文件

该脚本需要三个参数,第一个为文件名,第二个为章节名称,第三个为字段名称

#!/bin/bash

iniFile=$1
section=$2
option=$3


function readInIfile()
{

    iniFile=$1
    section=$2
    option=$3
    if [ "${section}" = "" ];then
        #通过如下两条命令可以解析成一个数组
        allSections=$(awk -F '[][]' '/\[.*]/{print $2}' ${iniFile})
        iniSections=(${allSections// /})
        echo "[info]:iniSections size:-${#iniSections[@]}- eles:-${iniSections[@]}- "
	return ${#iniSections[@]}
    elif [ "${section}" != "" ] && [ "${option}" = "" ];then
        #判断section是否存在
        allSections=$(awk -F '[][]' '/\[.*]/{print $2}' ${iniFile})
        echo $allSections|grep ${section}
        if [ "$?" = "1" ];then
            echo "[error]:section --${section}-- not exist!"
            return 0
        fi
        #正式获取options
        #a=(获取匹配到的section之后部分|去除第一行|去除空行|去除每一行行首行尾空格|将行内空格变为@G@(后面分割时为数组时,空格会导致误拆))
        a=$(awk "/\[${section}\]/{a=1}a==1"  ${iniFile}|sed -e'1d' -e '/^$/d'  -e 's/[ \t]*$//g' -e 's/^[ \t]*//g' -e 's/[ ]/@G@/g' -e '/\[/,$d' )
        b=(${a})
        for i in ${b[@]};do
          #剔除非法字符,转换@G@为空格并添加到数组尾
          if [ -n "${i}" ]||[ "${i}" i!= "@G@" ];then
              iniOptions[${#iniOptions[@]}]=${i//@G@/ }
          fi
        done
        echo "[info]:iniOptions size:-${#iniOptions[@]}- eles:-${iniOptions[@]}-"
	return ${iniOptions[@]}
    elif [ "${section}" != "" ] && [ "${option}" != "" ];then
 
       # iniValue=`awk -F '=' '/\['${section}'\]/{a=1}a==1&&$1~/'${option}'/{print $2;exit}' $iniFile|sed -e 's/^[ \t]*//g' -e 's/[ \t]*$//g'`
        iniValue=`awk -F '=' "/\[${section}\]/{a=1}a==1" ${iniFile}|sed -e '1d' -e '/^$/d' -e '/^\[.*\]/,$d' -e "/^${option}.*=.*/!d" -e "s/^${option}.*= *//"`
        echo "[info]:iniValue value:-${iniValue}-"
	return ${iniValue}
        fi
}


这篇关于shell读取config.ini文件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程