【问题标题】:How can I split a string based on a delimiter in bash? [duplicate]如何根据 bash 中的分隔符拆分字符串? [复制]
【发布时间】:2014-02-19 06:00:08
【问题描述】:

我在 .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

【问题讨论】:

标签: arrays linux string bash split


【解决方案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

【讨论】:

  • 使用for解析任意字符串通常不是一个好主意,因为结果会受到路径名扩展的影响:看看运行for w in $(echo "hello/Hi/*" | tr "/" " ") ; do echo $w; done时会发生什么。
【解决方案2】:
for host in "${hosts[@]}"; do
    IFS=, read ip hostname <<< "$host"
    echo "IP: $ip, HOSTNAME: $hostname"
done

【讨论】:

  • 我接受了这个答案,因为它看起来很简单!
猜你喜欢
  • 1970-01-01
  • 2011-08-04
  • 2019-09-19
  • 1970-01-01
  • 2011-10-03
  • 2020-04-18
  • 2020-04-11
  • 2012-02-14
  • 2010-10-29
相关资源
最近更新 更多