bash split string into array

29 篇文章 0 订阅

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 a simple code, the command's speed doesn't matter. Any ideas?

 

IFS=', ' read -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}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值