我已经在一个.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"
我如何在数组上循环,但是根据通信分配每个索引,并将值存储在变量中,类似的内容:
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,如果这有帮助
for host in "${hosts[@]}"; do
IFS=, read ip hostname <<< "$host"
echo "IP: $ip, HOSTNAME: $hostname"
done
尝试此-->
-
使用
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