根据我的情况,需要从配置文件中收集值。但是需要从配置文件中访问值而不指定密钥。
通过source command
我已经完成了以下
Configuration.conf
export Name = value
export Age = value
导出地址=值
Script.sh
source Configuration.conf
echo $Name
echo $Age
echo $Address
通过上面的方式,我可以访问配置文件中的值。
我想在不使用配置文件的密钥的情况下访问这些值。
在我的上述场景中,Key将以任何形式进行更改(但值与我的逻辑相似)。在脚本中,我必须在不知道密钥名称的情况下读取值。如下所示。
source Configuration.conf
while [ $1 ] // Here 1 is representing the first Key of the configuration file.
do
//My Logics
done
非常感谢任何帮助。
答案 0 :(得分:2)
我会使用sed
和cut
解析配置文件。像这样:
sed -n 's/export//p' conf.sh | while read expression ; do
key=$(cut -d= -f1 <<< "$expression")
value=$(cut -d= -f2 <<< "$expression")
# your logic comes here ...
echo "$key -> $value"
done
输出继电器:
Name -> value
Age -> value
Address -> value
答案 1 :(得分:2)
假设配置文件只包含var = value声明,每个声明占用一行。
configfile=./Configuration.conf
. "$configfile"
declare -A configlist
while IFS='=' read -r key val ; do
# skip empty / commented lines and obviously invalid input
[[ $key =~ ^[[:space:]]*[_[:alpha:]] ]] || continue
# Stripping up to the last space in $key removes "export".
# Using eval to approximate the shell's handling of lines like this:
# var="some thing with spaces" # and a trailing comment.
eval "configlist[${key##* }]=$val"
done < "$configfile"
# The keys are "${!configlist[@]}", the values are "${configlist[@]}"
#
#for key in "${!configlist[@]}" ; do
# printf '"%s" = "%s"\n' "$key" "${configlist[$key]}"
#done
for value in "${configlist[@]}" ; do
: your logic goes here
done
答案 2 :(得分:2)
使用grep从conf文件中提取密钥。使用variable indirection获取值。
keys=( $(grep -oP '\w+(?==)' conf.conf) )
for (( i=0; i < ${#keys[@]}; i++ )); do
printf "%d\t%s\n" $i "${keys[i]}"
done
echo
source conf.conf
for var in "${keys[@]}"; do
printf "%s\t=> %s\n" "$var" "${!var}"
done
0 Name
1 Age
2 Address
Name => name_value
Age => age_value
Address => addr_value