字符串分割到Bash中的数组 [英] Split string into an array in Bash

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

问题描述

在一个Bash脚本,我想一个线分割成块,并把它们放入数组。

行:

 法国巴黎,欧洲

我想有他们在这样一个数组:

 数组[0] =巴黎
阵列[1] =法国
数组[2] =欧洲

我想用简单的code,命令的速度没有关系。我该怎么办呢?


解决方案

  IFS =','读-r -a阵列<<< $字符串

要访问一个单独的元素:

 回声$ {数组[0]}

要遍历元素:

 在元素$ {数组[@]}

    回声$元素
DONE

要同时获得索引和值:

 在指数$ {!数组[@]}

    回声$指数$ {数组[索引]}
DONE

由于猛砸数组是稀疏的最后一个例子是很有用的。换句话说,你可以删除元素或添加元素,然后将指标是不连续的。

 取消设置数组[1]
数组[42] =地球

要获得数组中元素的个数:

 回声$ {#数组[@]}

如前所述,数组可以是稀疏的,所以你不应该用长度来获得最后一个元素。下面是如何在Bash的4.2及更高版本:

 回声$ {数组[-1]}

在Bash中的任何版本(从后2.05b以上地方):

 回声$阵列[@]:-1:1}

较大的负偏移从数组的最后选择更远。请注意,在旧的形式在减号前的空间。它是必需的。

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

The line:

Paris, France, Europe

I would like to have them in an array like this:

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

I would like to use simple code, the command's speed doesn't matter. How can I do it?

解决方案

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

To access an individual element:

echo "${array[0]}"

To iterate over the elements:

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

To get both the index and the value:

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

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[@]}"

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

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