在Bash中将带分隔符的字符串读入数组

时间:2022-12-23 15:42:44

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]}

outputs

输出

1
1.50
string

Somewhere I found a solution which doesn't work:

我在某个地方找到了一个行不通的解决方案:

arr=$(echo ${line})

If I run the echo statements above after this, I get:

如果我在此之后运行上面的echo语句,我得到:

1 1.50 string
[empty line]
[empty line]

I also tried

我也试过

IFS=" "
arr=$(echo ${line})

with the same result. Can someone help, please?

与相同的结果。有人能帮吗?

4 个解决方案

#1


236  

arr=($line)

or

read -a arr <<< $line

#2


32  

Try this:

试试这个:

arr=(`echo ${line}`);

#3


12  

In: arr=( $line ). The "split" comes associated with "glob".
Wildcards (*,? and []) will be expanded to matching filenames.

:arr =($)。“分割”与“glob”联系在一起。通配符(*,?将扩展到匹配文件名。

The correct solution is only slightly more complex:

正确的解决方案只是稍微复杂一点:

IFS=' ' read -a arr <<< "$line"

No globbing problem; the split character is set in $IFS, variables quoted.

没有globbing问题;分割字符设置为$IFS,引用变量。

#4


-7  

line="1 1.50 string"

arr=$( $line | tr " " "\n")

for x in $arr
do
echo "> [$x]"
done

#1


236  

arr=($line)

or

read -a arr <<< $line

#2


32  

Try this:

试试这个:

arr=(`echo ${line}`);

#3


12  

In: arr=( $line ). The "split" comes associated with "glob".
Wildcards (*,? and []) will be expanded to matching filenames.

:arr =($)。“分割”与“glob”联系在一起。通配符(*,?将扩展到匹配文件名。

The correct solution is only slightly more complex:

正确的解决方案只是稍微复杂一点:

IFS=' ' read -a arr <<< "$line"

No globbing problem; the split character is set in $IFS, variables quoted.

没有globbing问题;分割字符设置为$IFS,引用变量。

#4


-7  

line="1 1.50 string"

arr=$( $line | tr " " "\n")

for x in $arr
do
echo "> [$x]"
done