测试文件test.ini内容为:
[mysection1] #我是注释
mytestkey1=myvalue1 #我是注释
[mysection2]
mytestkey2=myvalue2
[mysection3]
mytestkey3=myvalue3
shell脚本testr.sh代码:
#!/bin/bash
declare -A myini
while read string;
do
# 获取section标题
if [[ $string =~ .*\[[^]]+\].* ]]; then
section=$(echo "$string" | grep -oP '\[.*\]' | sed 's/\[\|\]//g' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
echo $section
fi
# 获取section下的key-value
if [[ $string =~ .*=[^=]+ ]]; then
key=$(echo "$string" | awk -F '=' '{print $1}' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//' | sed 's/#.*//g')
value=$(echo "$string" | awk -F '=' '{print $2}' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//' | sed 's/#.*//g')
#echo $section- $key- $value-
myini[$section, $key]=$value
fi
done < test.ini
mykey="mytestkey2"
echo "-------------------r"
echo ${myini[mysection1, mytestkey1]}
echo ${myini[mysection2, $mykey]}
测试结果:文章来源:https://uudwc.com/A/woyYV
root@mypc:~# ./test.sh
mysection1
mysection2
mysection3
-------------------r
myvalue1
myvalue2
文章来源地址https://uudwc.com/A/woyYV