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

查看:40
本文介绍了如何在 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.

访问单个元素:

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天全站免登陆