Home > Blockchain >  Convert text to associative array in bash script
Convert text to associative array in bash script

Time:05-13

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?

CodePudding user response:

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

input="{'A': '1' 'B': '2' 'C': 'Associative_Array'}"
input2="{'A': '4' 'B': '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: ${arr1[$i]}" != "${arr2[$i]}"
  else
      echo "equal: ${arr1[$i]}" == "${arr2[$i]}"
 fi
done

Result:

difference: 1 != 4
difference: 2 != 5
equal: Associative_Array == Associative_Array

CodePudding user response:

suggesting single sed line:

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

result:

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