'Convert text to associative array in bash script [closed]

Hi I am new to bash scripting. I have a text as shown below

input = {'A': '1' 'B': '2' 'C': 'Associative_Array'}

I want to convert the above text into an associative array as shown below using bash scripting.

result = ([A]=1 [B]=2 [C]=Associative_Array)

What is the best way to do so?

Also I after converting into associative array, I want to compare two arrays

array_1 = ([A]=1 [B]=2 [C]=Associative_Array) and array_2 = ([A]=3 [B]=4 [C]=Associative_Array)

What would be the best way to do so?



Solution 1:[1]

Converting the variable to an array and comparing them element by element

input="{'A': '1' 'B': '2' 'C': 'Associative_Array' 'D': 'off'}"
input2="{'B': '4' 'A': '5' 'C': 'Associative_Array'}"
b=$(echo "$input" | sed -nre "s/'([A-Z])': *'([a-zA-Z0-9_]+)'/['\1']='\2'/gp" |  tr -d '{}' | tr "'" '"')
c=$(echo "$input2" | sed -nre "s/'([A-Z])': *'([a-zA-Z0-9_]+)'/['\1']='\2'/gp" |  tr -d '{}' | tr "'" '"')
#echo "$b"
declare -A arr1="($b)"
declare -A arr2="($c)"
#echo "${arr1['B']}"

for i in "${!arr1[@]}"
do
  if [ "${arr1[$i]}" != "${arr2[$i]}" ]; then
      echo "difference '$i': '${arr1[$i]}' != '${arr2[$i]}'"
  else
      echo "     equal '$i': '${arr1[$i]}' == '${arr2[$i]}'"
 fi
done

Result:

difference 'A': '1' != '5'
difference 'B': '2' != '4'
     equal 'C': 'Associative_Array' == 'Associative_Array'
difference 'D': 'off' != ''

Method 2: Convert input string to json and process it with jq

in1="{'A': '1' 'B': '2' 'C': 'Associative_Array' 'D': 'off'}"
# making var a json string
in1="$(echo "$in1"  | sed -rne "s/('[A-Z]': *'[a-zA-Z0-9_]+')/\1,/g ; s/,[}]/}/p" | tr "'" '"')"

declare -A arr1="($(echo "$in1"  | jq -rc 'to_entries[] | "[" + (.key|@sh) + "]=" + (.value|@sh)'))"

for k in "${!arr1[@]}"; do
  echo "key: $k, value: ${arr1[$k]}"
done

Result

key: A, value: 1
key: B, value: 2
key: C, value: Associative_Array
key: D, value: off

Solution 2:[2]

suggesting single sed line:

sed "{s|{'|([|;s|'}|)|;s|': '|]=|g;s|' '| [|g;s| = |=|}" input.txt

result:

input=([A]=1 [B]=2 [C]=Associative_Array)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Dudi Boy