简体   繁体   English

Bash脚本将带空格分隔标记的字符串转换为数组

[英]Bash script to convert a string with space delimited tokens to an array

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 它只打印出“第一”而没有别的

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. PS:您无法导出IFS并在同一命令中使用新值。 You have to declare it first, then use it's effects in the following command: 您必须先声明它,然后在以下命令中使用它的效果:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM