反向搜索ini部分

问题描述 投票:0回答:2

假设这个 .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

使用 bash,如何搜索 .ini 文件以匹配该值,然后加载该部分,在本例中为
this_one
?然后根据该部分加载
another_value

在这种情况下,结果将是

sure

为了清楚起见,另一个例子:如果系统在其环境中加载了

stv
,则结果是
xyz

bash shell ini
2个回答
0
投票

只要

$variable
不包含任何特殊内容,您就可以尝试 awk 段落模式,这使得它非常简单:

$ awk -v RS= "/$variable/" file
[this_one]
my_value=something
another_value=sure

0
投票

这是你想要的吗?

#!/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
© www.soinside.com 2019 - 2024. All rights reserved.