【问题标题】:Bash script to convert a string with space delimited tokens to an array用于将带有空格分隔标记的字符串转换为数组的 Bash 脚本
【发布时间】:2013-03-12 15:24:45
【问题描述】:

我有一个字符串

echo $STRING

给了

first second third fourth fifth

基本上是一个列表分隔的空格。

我如何获取该字符串并使其成为一个数组,以便

array[0] = first
array[1] = second

等等。

我试过了

IFS=' ' read -a list <<< $STRING

但是当我做一个

echo ${list[@]}

它只打印出“第一”而不是别的

【问题讨论】:

标签: linux arrays bash shell


【解决方案1】:

其实很简单:

list=( $STRING )

或更详细地说:

declare -a list=( $STRING )

PS:您无法导出 IFS 并在同一命令中使用新值。您必须先声明它,然后在以下命令中使用它的效果:

$ list=( first second third )
$ IFS=":" echo "${list[*]}"
first second third
$ IFS=":" ; echo "${list[*]}"
first:second:third

【讨论】:

  • 太棒了。但是它怎么知道要按什么分割呢?
  • IFS' 默认值为 `\t\n\r` 或类似的东西。当使用()-syntax 分配给数组时,括号之间的所有内容都会像命令的参数一样展开,将每个“参数”转换为数组的一个元素。
猜你喜欢
  • 2012-11-08
  • 2015-06-02
  • 1970-01-01
  • 2018-02-16
  • 2012-01-30
  • 1970-01-01
  • 2023-04-01
  • 2021-01-22
  • 1970-01-01
相关资源
最近更新 更多