Home > Blockchain >  Bash read dictionary file
Bash read dictionary file

Time:07-24

I have a dictionary file, call it 1.txt with the following content:

app1=1

app2=10

app3=2

app1=8

and so on.

From a bash script I would like to:

  1. call 1.txt
  2. read its content line by line
  3. get key into variable A
  4. get value into variable B

I tried:

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

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

which works just fine but I do not know how to wrap this into a bash function that calls the dictionary set on another file.

Would you please point out on this?

CodePudding user response:

@Author,

I tried the following at 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

CodePudding user response:

Probably this is what you want.

#!/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=%s\n' "$key" "${dict[$key]}"
done
  • Related