shell数组使用技巧

.数组定义

一对括号表示是数组,数组元素用“空格”符号分割开。

#define an array
arr1=(1 2 3 4 5 6 7 8 9 10)
arr2=("xiao" "ming" "ni" "hao" "hello" "world")

得到长度:也就是数组元素个数

用${#数组名[@或*]} 可以得到数组长度

#the length of an array, also means element number.
echo "----------------------------------------------------"
echo "length of arr1 = ${#arr1[@]}"
echo "length of arr2 = ${#arr2[*]}"

#the length of specific member
echo "----------------------------------------------------"
echo "the length of arr2[1] = ${#arr2[1]}"
echo "the length of arr2[3] = ${#arr2[3]}"

shell 获取字符变量的长度:

str="hellokity"
echo "the length of specific variable = ${#str}"

读取:

用${数组名[下标]} 下标是从0开始  下标是:*或者@ 得到整个数组内容

#all members of an array
echo "----------------------------------------------------"
echo "all member of arr1 = ${arr1[*]}"
echo "all member of arr2 = ${arr2[@]}"

#certain member of an array
echo "----------------------------------------------------"
echo "the first member of arr1 = ${arr1[0]}"
echo "the second member of arr2 = ${arr2[1]}"

赋值:

直接通过 数组名[下标] 就可以对其进行引用赋值,如果下标不存在,自动添加新一个数组元素

#assian to a certian member of array
echo "----------------------------------------------------"
echo "assign 100 to arr1[1]"
arr1[1]=100
echo "arr1[1] = ${arr1[1]}"
echo "arr1 = ${arr1[*]}"

echo "assign fuck to arr2[5]"
arr2[5]="fuck"
echo "arr2[5] = ${arr2[5]}"
echo "arr2 = ${arr2[@]}"

删除:

直接通过:unset 数组[下标] 可以清除相应的元素,不带下标,清除整个数据。

#unset command
echo "----------------------------------------------------"
unset arr1
echo "after unset arr1, arr1 = ${arr1[*]}"
arr1=(1 2 3 4 5)
echo "after re-assigned, arr1 = ${arr1[*]}"
unset arr1[1]
echo "after unset arr[1], arr1 = ${arr1[*]}"
echo "after unset arr[1], arr1 length = ${#arr1[*]}"

分片:

直接通过 ${数组名[@或*]:起始位置:长度} 切片原先数组,返回是字符串,中间用“空格”分开,因此如果加上”()”,将得到切片数组。

#section
echo "----------------------------------------------------"
arr1=(1 2 3 4 5 6 7 8 9 10)
echo "section 0-3 of arr1 = ${arr1[*]:0:3}"
echo "section 4-7 of arr1 = ${arr1[@]:4:7}"
arr2=(${arr1[@]:3:5})
echo "arr2 = ${arr2[*]}"

替换:

调用方法是:${数组名[@或*]/查找字符/替换字符} 该操作不会改变原先数组内容,如果需要修改,可以看下面例子,重新定义数据。

#replace string
echo "----------------------------------------------------"
arr1=(1 2 3 4 5)
echo "replace 100 to 3 in arr1:  ${arr1[@]/3/100}"
echo "arr1 = ${arr1[*]}"
arr1=(${arr1[@]/3/100})
echo "after replace 3 with 100, arr1 = ${arr1[*]}"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值