0

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 !!

2
  • What do you need help with exactly? Do you understand why the problem is happening? Have you considered using an associative array instead? Commented Apr 27, 2022 at 22:09
  • The c2.url"$j"=$LB does not work. In a variable assignment, you can't have a parameter expansion to the left of the equal sign. Therefore, bash interprets this as a command. You could use eval, or a nameref, or an associative array. In your case, an associative array would perhaps most suitable, but IMO the main problem in your program is that you create 4 child processes for each line of the file sample. You could instead simply loop over the lines of your file and from each line assign your array (no child process needed). Commented Apr 28, 2022 at 7:58

1 Answer 1

2

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]}"
Sign up to request clarification or add additional context in comments.

1 Comment

or just while IFS="'" read -r _ key _ url _; do and avoid the cuts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.