我在.sh文件中定义了一个数组,如下所示:
hosts=(NODE IPS)
hosts[0]="1.110,Node-01"
hosts[1]="1.111,Node-02"
hosts[2]="1.112,Node-03"
hosts[3]="1.113,Node-04"
hosts[4]="1.114,Node-05"
hosts[5]="1.115,Node-06"
如何循环遍历数组,但是根据commma拆分每个索引,并将值存储在变量中,如下所示:
for index in ${!hosts[*]}
do
ip = ## some way to split the string, and get the left side of the index
hostname = ## some way to split the string, and get the right side of the index
## do something with the above variables
echo "IP: $ip HOSTNAME: $hostname"
done
如果这有帮助,我正在使用linux
答案 0 :(得分:3)
for host in "${hosts[@]}"; do
IFS=, read ip hostname <<< "$host"
echo "IP: $ip, HOSTNAME: $hostname"
done
答案 1 :(得分:1)
试试这个-->
使用tr
打破字符串
for w in $(echo "hello/Hi/Bye" | tr "/" " ") ; do echo $w; done
输出
Hello
Hi
Bye
2
。可以使用awk
声明。示例--->
使用“:”作为以下示例的分隔符
$ echo "abc:def" | awk -F':' '{print "field1: "$1 "\nfield2: "$2}'
输出
field1: abc
field2: def