Bash读取字典文件



我有一个字典文件,称之为1.txt,内容如下:

app1=1
app2=10
app3=2
app1=8

等等

从一个bash脚本我想:

  1. 调用1.text
  2. 逐行阅读其内容
  3. 将密钥放入变量A
  4. 将值代入变量B

我试过了:

var1=${for KEY in "${!dict[@]}"; do echo $KEY; done

var2=${for KEY in "${!dict[@]}"; do echo $dict[$KEY]}; done

它工作得很好,但我不知道如何将其封装到一个bash函数中,该函数调用另一个文件上的字典集。

请你指出这一点好吗?

也许这就是您想要的。

#!/bin/bash
declare -A dict
# Read the file into associative array "dict"
read_into_dict () {
    while read -r line; do
        [[ $line = *=* ]] && dict[${line%%=*}]=${line#*=}
    done < "$1"
}
read_into_dict 1.txt
# Print out the dict
for key in "${!dict[@]}"; do
    printf '%s=%sn' "$key" "${dict[$key]}"
done

@M。Nejat Aydin,我在localhost上尝试了以下操作。``


$ cat 73095065.sh
#!/bin/bash
declare -A dict
for EACHLN in $(cat 1.txt)
do
KEY=$(echo "$EACHLN" | sed "s/=.//;")
VALUE=$(echo "$EACHLN" | sed "s/.=//;")
if [ "${dict[$KEY]}" = "" ]
then
dict["$KEY"]="$VALUE"
else
echo "FOUND DUPLICATE KEY AT 1.txt"
echo "HENCE NOT SETTING dict["$KEY"] TO $VALUE AGAIN."
echo "CURRENT LINE: $EACHLN"
echo "OLD dict value: $KEY=${dict["$KEY"]}"
fi
done
echo "EXISTING DICT VALUES:"
for KEY in "${!dict[@]}"
do
echo "KEY $KEY VALUE ${dict[$KEY]}"
done

Sample output:

$ ./73095065.sh
FOUND DUPLICATE KEY AT 1.txt
HENCE NOT SETTING dict[app1] TO 8 AGAIN.
CURRENT LINE: app1=8
OLD dict value: app1=1
EXISTING DICT VALUES:
KEY app3 VALUE 2
KEY app2 VALUE 10
KEY app1 VALUE 1

相关内容

  • 没有找到相关文章

最新更新