简体   繁体   English

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

[英]Reading a delimited string into an array in 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]}

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? 有人可以帮帮忙吗?

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. 至关重要的是不要使用引号,因为这样可以解决问题。

试试这个:

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

In: arr=( $line ) . 在: arr=( $line ) The "split" comes associated with "glob". “分裂”与“glob”相关联。
Wildcards ( * , ? and [] ) will be expanded to matching filenames. 通配符( *?[]将扩大到匹配的文件名。

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设置,引用变量。

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.txt and c.txt , then executing the code would produce the following output. 如果当前目录包含文件a.txtb.txtc.txt ,则执行代码将产生以下输出。

a
b
c d
*
a.txt
b.txt
c.txt
line="1 1.50 string"

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

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

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

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