巴什解析阵列从配置文件 [英] Bash Parse Arrays From Config File
问题描述
我需要包含在文件中为每个部分的数组:
I need to have an array for each "section" in the file containing:
[array0]
value1=asdf
value2=jkl
[array1]
value1=1234
value2=5678
我希望能够找回这样这些值:
I want to be able to retrieve these values like this:
echo ${array0[value1]}
echo ${array0[value2]}
echo ${array1[value1]}
echo ${array1[value2]}
这是如何做到这一点有什么想法? (解释将是一个奖金)
Any thoughts on how to accomplish this? (Explanations would be a bonus)
我已经阅读这些anwsers但没有不正是我想要做的。
I've already read these anwsers but none do exactly what I want to do.
<一个href=\"http://stackoverflow.com/questions/4434797/read-a-config-file-in-bash-without-using-source\">Read BASH中的配置文件,而无需使用&QUOT;源&QUOT;
<一个href=\"http://stackoverflow.com/questions/15684646/array-like-data-structure-in-bash-config-file\">Array像在bash(配置文件)?
推荐答案
在bash V4,使用关联数组,存储从配置文件作为实际bash的变量属性:
with bash v4, using associative arrays, store the properties from the config file as actual bash variables:
$ while read line; do
if [[ $line =~ ^"["(.+)"]"$ ]]; then
arrname=${BASH_REMATCH[1]}
declare -A $arrname
elif [[ $line =~ ^([_[:alpha:]][_[:alnum:]]*)"="(.*) ]]; then
declare ${arrname}[${BASH_REMATCH[1]}]="${BASH_REMATCH[2]}"
fi
done < config.conf
$ echo ${array0[value1]}
asdf
$ echo ${array1[value2]}
5678
$ for i in "${!array0[@]}"; do echo "$i => ${array0[$i]}"; done
value1 => asdf
value2 => jkl
$ for i in "${!array1[@]}"; do echo "$i => ${array1[$i]}"; done
value1 => 1234
value2 => 5678
这篇关于巴什解析阵列从配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!