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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9293887/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:22:35  来源:igfitidea点击:

Reading a delimited string into an array in Bash

arraysstringbashshell

提问by Nikola Novak

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?

结果相同。有人可以帮忙吗?

回答by kev

In order to convert a string into an array, please use

要将字符串转换为数组,请使用

arr=($line)

or

或者

read -a arr <<< $line

It is crucial not to use quotes since this does the trick.

重要的是不要使用引号,因为这可以解决问题。

回答by Randy

Try this:

尝试这个:

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

回答by Isaac

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

在:arr=( $line )。“分裂”与“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.

没有通配问题;拆分字符设置在$IFS,引用变量。

回答by David Anderson

If you need parameter expansion, then try:

如果您需要参数扩展,请尝试:

eval "arr=($line)"

For example, take the following code.

例如,采用以下代码。

line='a b "c d" "*" *'
eval "arr=($line)"
for s in "${arr[@]}"; do 
    echo "$s"
done

If the current directory contained the files a.txt, b.txtand c.txt, then executing the code would produce the following output.

如果当前目录包含文件a.txt,b.txtc.txt,则执行代码将产生以下输出。

a
b
c d
*
a.txt
b.txt
c.txt

回答by Hitesh

line="1 1.50 string"

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

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