在 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屋!
查看全文