標籤:
前幾日項目組內出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/bashput_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 1fitypeset -A resultput_arrayget_array $1 $2
shell 類比二維數組解析設定檔