Issue
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:
- call 1.txt
- read its content line by line
- get key into variable A
- 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?
Solution
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
Answered By - M. Nejat Aydin Answer Checked By - Candace Johnson (WPSolving Volunteer)