将带有空格分隔标记的字符串转换为数组的 Bash 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15575976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash script to convert a string with space delimited tokens to an array
提问by Dan
I have a string
我有一个字符串
echo $STRING
which gives
这使
first second third fourth fifth
basically a list separated spaces.
基本上是一个列表分隔的空格。
how do i take that string and make it an array so that
我如何获取该字符串并将其设为数组,以便
array[0] = first
array[1] = second
etc..
等等..
I have tried
我试过了
IFS=' ' read -a list <<< $STRING
but then when i do an
但是当我做一个
echo ${list[@]}
it only prints out "first" and nothing else
它只打印出“第一个”,没有别的
回答by svckr
It's simple actually:
其实很简单:
list=( $STRING )
Or more verbosely:
或者更详细地说:
declare -a list=( $STRING )
PS: You can't export IFS and use the new value in the same command. You have to declare it first, then use it's effects in the following command:
PS:您不能在同一命令中导出 IFS 并使用新值。您必须先声明它,然后在以下命令中使用它的效果:
$ list=( first second third )
$ IFS=":" echo "${list[*]}"
first second third
$ IFS=":" ; echo "${list[*]}"
first:second:third

