码迷,mamicode.com
首页 > 编程语言 > 详细

shell 模拟二维数组解析配置文件

时间:2015-04-25 22:45:06      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:

前几日项目组内出shell OJ题进行练习, 题目大概为:

现有配置文件conf.ini如下,编写shell,输入title和key,输出其值,

如输入FIFO1 a1 ,则输出11

#this is a config file

[FIFO1]
a1=11 b1=12 c1=13

[FIFO2]
a2=21 b2=22 c2=23

[FIFO3]
a3=31 b3=32 c3=33

 

恰因这几日内在学习数组的用法,故使用shell来模拟二维数组,现博客之,以飨同学,共研讨。

注:本解法未考虑性能,实现技巧等,只在于实验模拟二维数组。

#!/bin/bash

put_array(){
    cat conf.ini | egrep -v "^[[:blank:]]*#|^[[:blank:]]*$" |sed s/#.*//g  >file_$$

    while read line
    do
        if echo $line | grep -qs "\[" ;then
            title=$(echo $line | grep -oP (?<=\[)\w*(?=\]))
        else
            typeset integer index=0
            key_val=($(echo $line|xargs -d =))
            for i in ${key_val[*]}
            do
                let index=index+1
                if [ $(echo "$index%2"|bc) -ne 0 ];then 
                    key=$i
                else 
                    value=$i
                    result[$title,$key]=$value
                fi
            done 
        fi
    
    done  <file_$$
    rm file_$$
}

get_array()
{
    in_title=$1
    in_key=$2

    for i in ${!result[*]}
    do
        [ "$i" == "$in_title,$in_key" ] && echo ${result[$i]}
    done
}

if [ $# -ne 2 ];then
    echo "input num error"
    exit 1
fi

typeset -A result
put_array
get_array $1 $2

 

shell 模拟二维数组解析配置文件

标签:

原文地址:http://www.cnblogs.com/mazi12/p/4356783.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!