[英]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.(ie)if I do echo $c2.url0 then output should be "k8s-abc1.amazonaws.com: 1000".Similarly for other keys.从这里我想获取网址并将其分配给与键同名的变量。(即)如果我回显 $c2.url0 那么 output 应该是“k8s-abc1.amazonaws.com:1000”。与其他键类似.
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 !!请帮忙 !!
Bash doesn't use a dot to separate keys. Bash 不使用点分隔键。
First, you need to declare an associative array.首先,您需要声明一个关联数组。
declare -A c2
Then, you can use syntax similar to the array bash syntax:然后,您可以使用类似于数组 bash 语法的语法:
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]}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.