如何用Bash根据环境变量值匹配INI文件节并获取对应字段值
Bash 匹配INI文件指定值并提取对应节的字段
假设我们有如下INI文件(命名为config.ini):
[section_x]
my_value=abc
another_value=def[section_2]
my_value=stv
another_value=xyz[this_one]
my_value=something
another_value=sure
系统环境变量TARGET_VALUE已加载目标值(比如something),可以用以下awk命令完成匹配并提取对应字段:
awk -v target="$TARGET_VALUE" ' /^\[.*\]$/ { current_section = $0 } $1 == "my_value" && $2 == target { match_section = current_section } $1 == "another_value" && current_section == match_section { print $2 } ' config.ini FS='='
命令逻辑说明
-v target="$TARGET_VALUE":把环境变量TARGET_VALUE的值传入awk作为内部变量target/^\[.*\]$/ { current_section = $0 }:匹配节标题行(比如[this_one]),记录当前所在的节$1 == "my_value" && $2 == target { match_section = current_section }:当找到my_value等于目标值的行时,记录对应的匹配节$1 == "another_value" && current_section == match_section { print $2 }:在匹配到的节里,找到another_value行并输出其值FS='=':指定字段分隔符为等号
示例测试
- 当环境变量值为
something时:export TARGET_VALUE="something" # 执行命令后输出:sure - 当环境变量值为
stv时:export TARGET_VALUE="stv" # 执行命令后输出:xyz
内容的提问来源于stack exchange,提问作者Kevin C
相关产品推荐
相关产品推荐

