假设这个 .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
假设系统在其环境变量中加载了值
something
。this_one
?然后根据该部分加载 another_value
。
在这种情况下,结果将是
sure
。
为了清楚起见,另一个例子:如果系统在其环境中加载了
stv
,则结果是 xyz
。
只要
$variable
不包含任何特殊内容,您就可以尝试 awk 段落模式,这使得它非常简单:
$ awk -v RS= "/$variable/" file
[this_one]
my_value=something
another_value=sure
这是你想要的吗?
#!/bin/bash
loaded_value=$1
#reading the .ini file line by line
while IFS= read -r line
do
if [[ $line =~ ^\[(.*)\] ]]; then
section=${BASH_REMATCH[1]}
else
# Split the line into key and value
IFS='=' read -ra pair <<< "$line"
key=${pair[0]}
value=${pair[1]}
if [[ $value == "$loaded_value" ]]; then
matched_section=$section
matched_key=$key
break
fi
fi
done < file.ini
while IFS= read -r line
do
if [[ $line =~ ^$matched_key=(.*) ]]; then
matched_value=${BASH_REMATCH[1]}
break
fi
done < file.ini
echo "Matched section: $matched_section"
echo "Matched value: $matched_value"
用法
bash ini_search.sh something