使用 SHELL 解析 INI 檔

    INI 檔的格式

    [Section-A]
    Var1=XXX
    Var2=XXX
    
    [Section-B]
    Var1=XXX
    Var2=XXX 
    

    範例一

    使用:myscript.ksh my.ini <SectionName> <VariableName>
    NOTE:在同一個 Section,相同 VariableName 只能有一個值。

    #!/bin/ksh
    #INI_FILE=path/to/file.ini
    #INI_SECTION=TheSection
    # BEGIN parse-ini-file.sh
    # SET UP THE MINIMUM VARS FIRST
    
    #alias sed=/usr/local/bin/sed
    
    INI_FILE=$1
    INI_SECTION=$2
    INI_NAME=$3
    INI_VALUE=""
    
    eval `sed -e 's/[[:space:]]*\=[[:space:]]*/=/g' \
        -e 's/;.*$//' \
        -e 's/[[:space:]]*$//' \
        -e 's/^[[:space:]]*//' \
        -e "s/^\(.*\)=\([^\"']*\)$/\1=\"\2\"/" \
       < $INI_FILE  \
        | sed -n -e "/^\[$INI_SECTION\]/,/^\s*\[/{/^[^;].*\=.*/p;}"`
    
    TEMP_VALUE=`echo "$"$INI_NAME`
    echo `eval echo $TEMP_VALUE`
    

    範例三

    reference to undefined name 'syntax' Exception of type 'MindTouch.Deki.Script.Runtime.DekiScriptUndefinedNameException' was thrown. (click for details)

     Usage:

    # parse the config file called 'myfile.ini', with the following
    # contents::
    #   [sec2]
    #   var2='something'
    cfg.parser 'myfile.ini'
    
    # enable section called 'sec2' (in the file [sec2]) for reading
    cfg.section.sec2
    
    # read the content of the variable called 'var2' (in the file
    # var2=XXX). If your var2 is an array, then you can use
    # ${var[index]}
    echo "$var2"
    
    標籤 (Edit tags)
    • No tags
    您必須 登入 才能發佈評論。
    Powered by MindTouch Core