gpt4 book ai didi

linux - 如何使用shell脚本读取属性文件

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:15:36 24 4
gpt4 key购买 nike

如何使用shell脚本读取config.properties文件?

示例文件:

key1 = This is 1st value

key2 = this is 2nd value

key3
  1. 显示所有键和值。
  2. 如何检查哪个键没有值?
  3. 输入键相关值显示的任何键。

最佳答案

尝试以下操作:

#!/bin/bash

# Read configuration into an associative array
declare -A CONFIG
# IFS is the 'internal field separator'. In this case, your file uses '='
IFS="="
while read -r key value
do
if [ -n $value ]; then
CONFIG[$key]=$value
else
CONFIG[$key]=$value
fi
done < YOUR_CONFIG_FILENAME
unset IFS

# If a parameter is passed, look it up by that, else print everything.
if [ $1 ]; then
if [ -n ${CONFIG[$1]} ]; then
echo "Key: $1, Value: ${CONFIG[$1]}"
else
echo "The key '$1' does not exist"
fi
else
for key in "${!CONFIG[@]}"; do
if [ -n ${CONFIG[$key]} ]; then
echo "Key: $key, Value: ${CONFIG[$key]}"
else
echo "Key: $key has no value"
fi
done
fi

exit $?

它会读入配置文件中的所有键名,如果没有为该键设置值,它会通知您,满足您的要求(1)和(2)。

虽然我不太明白(3)的要求是什么

“3)输入任意一个key相关值显示的key”根据该要求更新脚本。

关于linux - 如何使用shell脚本读取属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30724170/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com