Arrays 如何在bash中基于分隔符拆分字符串?

Arrays 如何在bash中基于分隔符拆分字符串?,arrays,linux,string,bash,split,Arrays,Linux,String,Bash,Split,我在.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

我在.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
如果这有助于“${hosts[@]}”中主机的

,那么我正在使用linux;做
for host in "${hosts[@]}"; do
    IFS=, read ip hostname <<< "$host"
    echo "IP: $ip, HOSTNAME: $hostname"
done
如果为“${hosts[@]}”中的主机读取ip主机名
;做
如果为,则读取ip主机名尝试此
-->

  • 使用
    tr
    将字符串拆分

    for w in $(echo "hello/Hi/Bye" | tr "/" " ") ; do echo $w; done
    
    输出

    Hello
    Hi
    Bye
    
    field1: abc
    field2: def
    
  • 二, . 可以使用
    awk
    语句。示例
    -->
    使用“:”作为以下示例的分隔符

    $ echo "abc:def" | awk -F':' '{print "field1: "$1 "\nfield2: "$2}'
    
    输出

    Hello
    Hi
    Bye
    
    field1: abc
    field2: def
    
    试试这个
    -->

  • 使用
    tr
    将字符串拆分

    for w in $(echo "hello/Hi/Bye" | tr "/" " ") ; do echo $w; done
    
    输出

    Hello
    Hi
    Bye
    
    field1: abc
    field2: def
    
  • 二, . 可以使用
    awk
    语句。示例
    -->
    使用“:”作为以下示例的分隔符

    $ echo "abc:def" | awk -F':' '{print "field1: "$1 "\nfield2: "$2}'
    
    输出

    Hello
    Hi
    Bye
    
    field1: abc
    field2: def
    

    尝试此
    -->
    已在帖子中回答尝试此
    -->
    已在帖子中回答使用
    for
    解析任意字符串通常不是一个好主意,因为结果受路径名扩展的影响:查看在$(echo“hello/Hi/*”| tr“/”)中为w运行
    时发生的情况;不要重复$w;完成
    。使用
    for
    解析任意字符串通常不是一个好主意,因为结果受路径名扩展的影响:查看在$中为w运行
    时会发生什么(echo“hello/Hi/*”| tr“/”);不要重复$w;完成
    。我接受了这个答案,因为它看起来很简单!我接受了这个答案,因为它看起来很简单!