在Bash中将定界字符串读入数组 [英] Reading a delimited string into an array in Bash
本文介绍了在Bash中将定界字符串读入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个变量,其中包含一个以空格分隔的字符串:
I have a variable which contains a space-delimited string:
line="1 1.50 string"
我想用空格作为分隔符分割该字符串并将结果存储在数组中,以便执行以下操作:
I want to split that string with space as a delimiter and store the result in an array, so that the following:
echo ${arr[0]}
echo ${arr[1]}
echo ${arr[2]}
输出
1
1.50
string
我在某个地方找到了行不通的解决方案:
Somewhere I found a solution which doesn't work:
arr=$(echo ${line})
如果在此之后运行上面的echo语句,则会得到:
If I run the echo statements above after this, I get:
1 1.50 string
[empty line]
[empty line]
我也尝试过
IFS=" "
arr=$(echo ${line})
具有相同的结果.有人可以帮忙吗?
with the same result. Can someone help, please?
推荐答案
要将字符串转换为数组,请使用
In order to convert a string into an array, please use
arr=($line)
或
read -a arr <<< $line
至关重要的是不要使用引号,因为这样做可以解决问题.
It is crucial not to use quotes since this does the trick.
这篇关于在Bash中将定界字符串读入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文