Khumar
Khumar

Reputation: 336

Assign values to variables by reading from a file in bash

I have a sample file which looks like below.

cat sample
'c2.url0' :  'k8s-abc1.amazonaws.com : 1000'
'c2.url1' :  'k8s-abc2.amazonaws.com : 1001'
'c2.url2' :  'k8s-xyz1.amazonaws.com : 1003'

From this I want to get urls and assign it to a variable with same name as key.(i.e)if I do echo $c2.url0 then output should be "k8s-abc1.amazonaws.com : 1000".Similarly for other keys.

echo $c2.url0 should print --> "k8s-abc1.amazonaws.com : 1000"
echo $c2.url1 should print --> "k8s-abc2.amazonaws.com : 1001"
echo $c2.url2 should print --> "k8s-xyz1.amazonaws.com : 1003"

I have tried like

  lenc2=$(cat sample | grep c2|wc -l)

#Get LBs of cluster_2 ###
  j=0
    while [ $j -lt $lenc2 ]
  do
        LB=$(cat sample | grep c2.url$j| awk -F: '{print  $(NF-1),":",$(NF)}'|sed "s/'/\"/g")
        c2.url"$j"=$LB
        j=$(( j + 1 ))
  done

But while assigning value to variable i am facing issue.

 c2.url0=: command not found
 c2.url1=: command not found
 c2.url2=: command not found

Please help !!

Upvotes: 0

Views: 56

Answers (1)

choroba
choroba

Reputation: 242343

Bash doesn't use a dot to separate keys.

First, you need to declare an associative array.

declare -A c2

Then, you can use syntax similar to the array bash syntax:

while read line ; do
    key=$(cut -f2 -d\' <<< "$line")
    url=$(cut -f4 -d\' <<< "$line")
    
    c2[${key#c2.}]=$url  # Remove "c2." from the left.
done < sample

echo "${c2[url0]}"

Upvotes: 2

Related Questions