天天看點

linux shell 中數組使用方法介紹

linux shell在程式設計方面比windows 批處理強大太多,不管是在循環、運算。已經資料類型方面都是不能比較的。 以下是個人在使用時候,對它在數組方面一些操作進行的總結。

1.數組定義

[chengmo@centos5 ~]$ a=(1 2 3 4 5)

[chengmo@centos5 ~]$ echo $a

1

一對括号表示是數組,數組元素用“空格”符号切割開。

2.數組讀取與指派

得到長度:

[chengmo@centos5 ~]$ echo ${#a[@]}

5

用${#數組名[@或*]} 能夠得到數組長度

讀取:

[chengmo@centos5 ~]$ echo ${a[2]}

3

[chengmo@centos5 ~]$ echo ${a[*]}

1 2 3 4 5

用${數組名[下标]} 下标是從0開始 下标是:*或者@ 得到整個數組内容

指派:

[chengmo@centos5 ~]$ a[1]=100

1 100 3 4 5

[chengmo@centos5 ~]$ a[5]=100

1 100 3 4 5 100

直接通過 數組名[下标] 就能夠對其進行引用指派,假設下标不存在,自己主動增加新一個數組元素

删除:

[chengmo@centos5 ~]$ unset a

[chengmo@centos5 ~]$ unset a[1]

1 3 4 5

[chengmo@centos5 ~]$ echo ${#a[*]}

4

直接通過:unset 數組[下标] 能夠清除對應的元素,不帶下标,清除整個資料。

3.特殊使用

分片:

1 2 3

2 3 4 5

[chengmo@centos5 ~]$ echo ${#c[@]}

[chengmo@centos5 ~]$ echo ${c[*]}

直接通過 ${數組名[@或*]:起始位置:長度} 切片原先數組,傳回是字元串,中間用“空格”分開,是以假設加上”()”,将得到切片數組,上面樣例:c 就是一個新資料。

替換:

[chengmo@centos5 ~]$ echo ${a[@]/3/100}

1 2 100 4 5

[chengmo@centos5 ~]$ echo ${a[@]}

[chengmo@centos5 ~]$ a=(${a[@]/3/100})

調用方法是:${數組名[@或*]/查找字元/替換字元} 該操作不會改變原先數組内容,假設須要改動,能夠看上面樣例,又一次定義資料。

從上面講到的,大家能夠發現linux shell 的數組已經非常強大了,常見的操作已經綽綽有餘了。

繼續閱讀