如何在Bash中将字符串拆分为数组? [英] How to split a string into an array in Bash?

查看:116
本文介绍了如何在Bash中将字符串拆分为数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Bash脚本中,我想将一行分割成几部分并将它们存储在数组中.

In a Bash script, I would like to split a line into pieces and store them in an array.

例如,给出以下行:

Paris, France, Europe

我希望得到的数组看起来像这样:

I would like to have the resulting array to look like so:

array[0] = Paris
array[1] = France
array[2] = Europe

一个简单的实现是可取的;速度没关系.我该怎么办?

A simple implementation is preferable; speed does not matter. How can I do it?

推荐答案

IFS=', ' read -r -a array <<< "$string"

请注意,将 $ IFS 中的字符分别视为分隔符,因此在这种情况下,字段可以用 逗号或空格而不是序列号分隔.这两个字符.有趣的是,当输入中出现逗号空间时,不会创建空字段,因为空格是经过特殊处理的.

Note that the characters in $IFS are treated individually as separators so that in this case fields may be separated by either a comma or a space rather than the sequence of the two characters. Interestingly though, empty fields aren't created when comma-space appears in the input because the space is treated specially.

要访问单个元素,请执行以下操作:

To access an individual element:

echo "${array[0]}"

要遍历元素:

for element in "${array[@]}"
do
    echo "$element"
done

要同时获取索引和值:

for index in "${!array[@]}"
do
    echo "$index ${array[index]}"
done

最后一个示例很有用,因为Bash数组稀疏.换句话说,您可以删除一个元素或添加一个元素,然后索引不连续.

The last example is useful because Bash arrays are sparse. In other words, you can delete an element or add an element and then the indices are not contiguous.

unset "array[1]"
array[42]=Earth

要获取数组中的元素数:

To get the number of elements in an array:

echo "${#array[@]}"

如上所述,数组可以是稀疏的,因此您不应该使用长度来获取最后一个元素.这是在Bash 4.2及更高版本中的操作方式:

As mentioned above, arrays can be sparse so you shouldn't use the length to get the last element. Here's how you can in Bash 4.2 and later:

echo "${array[-1]}"

在任何版本的Bash中(从2.05b之后的版本开始):

in any version of Bash (from somewhere after 2.05b):

echo "${array[@]: -1:1}"

更大的负偏移量选择距离数组末端更远的位置.请注意在较早的形式中减号之前的空格.这是必需的.

Larger negative offsets select farther from the end of the array. Note the space before the minus sign in the older form. It is required.

这篇关于如何在Bash中将字符串拆分为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆