Linux Shell 數(shù)組的創(chuàng)建及使用技巧
linux shell在編程方面比windows 批處理強(qiáng)大太多,無論是在循環(huán)、運(yùn)算。已經(jīng)數(shù)據(jù)類型方面都是不能比較的。 下面是個(gè)人在使用時(shí)候,對它在數(shù)組方面一些操作進(jìn)行的總結(jié)。
1.數(shù)組定義
[chengmo@centos5 ~]$ a=(1 2 3 4 5) [chengmo@centos5 ~]$ echo $a
一對括號表示是數(shù)組,數(shù)組元素用“空格”符號分割開。
2.數(shù)組讀取與賦值
得到長度:
[chengmo@centos5 ~]$ echo ${#a[@]} 5
用${#數(shù)組名[@或*]} 可以得到數(shù)組長度
讀?。?br />
[chengmo@centos5 ~]$ echo ${a[2]} 3 [chengmo@centos5 ~]$ echo ${a[*]} 1 2 3 4 5
用${數(shù)組名[下標(biāo)]} 下標(biāo)是從0開始 下標(biāo)是:*或者@ 得到整個(gè)數(shù)組內(nèi)容
賦值:
[chengmo@centos5 ~]$ a[1]=100 [chengmo@centos5 ~]$ echo ${a[*]} 1 100 3 4 5 [chengmo@centos5 ~]$ a[5]=100 [chengmo@centos5 ~]$ echo ${a[*]} 1 100 3 4 5 100
直接通過 數(shù)組名[下標(biāo)] 就可以對其進(jìn)行引用賦值,如果下標(biāo)不存在,自動添加新一個(gè)數(shù)組元素
刪除:
[chengmo@centos5 ~]$ a=(1 2 3 4 5) [chengmo@centos5 ~]$ unset a [chengmo@centos5 ~]$ echo ${a[*]} [chengmo@centos5 ~]$ a=(1 2 3 4 5) [chengmo@centos5 ~]$ unset a[1] [chengmo@centos5 ~]$ echo ${a[*]} 1 3 4 5 [chengmo@centos5 ~]$ echo ${#a[*]} 4
直接通過:unset 數(shù)組[下標(biāo)] 可以清除相應(yīng)的元素,不帶下標(biāo),清除整個(gè)數(shù)據(jù)。
3.特殊使用
分片:
[chengmo@centos5 ~]$ a=(1 2 3 4 5) [chengmo@centos5 ~]$ echo ${a[@]:0:3} 1 2 3 [chengmo@centos5 ~]$ echo ${a[@]:1:4} 2 3 4 5 [chengmo@centos5 ~]$ c=(${a[@]:1:4}) [chengmo@centos5 ~]$ echo ${#c[@]} 4 [chengmo@centos5 ~]$ echo ${c[*]} 2 3 4 5
直接通過 ${數(shù)組名[@或*]:起始位置:長度} 切片原先數(shù)組,返回是字符串,中間用“空格”分開,因此如果加上”()”,將得到切片數(shù)組,上面例子:c 就是一個(gè)新數(shù)據(jù)。
替換:
[chengmo@centos5 ~]$ a=(1 2 3 4 5) [chengmo@centos5 ~]$ echo ${a[@]/3/100} 1 2 100 4 5 [chengmo@centos5 ~]$ echo ${a[@]} 1 2 3 4 5 [chengmo@centos5 ~]$ a=(${a[@]/3/100}) [chengmo@centos5 ~]$ echo ${a[@]} 1 2 100 4 5
調(diào)用方法是:${數(shù)組名[@或*]/查找字符/替換字符} 該操作不會改變原先數(shù)組內(nèi)容,如果需要修改,可以看上面例子,重新定義數(shù)據(jù)。
從上面講到的,大家可以發(fā)現(xiàn)linux shell 的數(shù)組已經(jīng)很強(qiáng)大了,常見的操作已經(jīng)綽綽有余了。
相關(guān)文章
詳解Linux下的sudo及其配置文件/etc/sudoers的詳細(xì)配置
這篇文章主要介紹了詳解Linux下的sudo及其配置文件/etc/sudoers的詳細(xì)配置的相關(guān)資料,需要的朋友可以參考下2017-05-05sed或awk處理文件最后一行的實(shí)現(xiàn)方法
sed或awk處理文件最后一行,供大家學(xué)習(xí)參考2013-02-02使用scp獲取遠(yuǎn)程linux服務(wù)器上的文件 linux遠(yuǎn)程拷貝文件
scp是secure copy的簡寫,用于在Linux下進(jìn)行遠(yuǎn)程拷貝文件的命令,scp傳輸是加密的,下面看一下詳細(xì)使用方法吧2014-01-01shell腳本學(xué)習(xí)指南[三](Arnold Robbins & Nelson H.F. Beebe著)
這篇文章主要介紹了shell腳本學(xué)習(xí)指南[三](Arnold Robbins & Nelson H.F. Beebe著),需要的朋友可以參考下2014-02-02shell檢測某個(gè)文件/文件夾是否存在詳細(xì)實(shí)例
shell是一個(gè)用?C?語言編寫的程序,它是用戶使用Linux的橋梁,下面這篇文章主要給大家介紹了關(guān)于shell檢測某個(gè)文件/文件夾是否存在的相關(guān)資料,需要的朋友可以參考下2023-06-06使用shell腳本采集系統(tǒng)cpu、內(nèi)存、磁盤、網(wǎng)絡(luò)等信息
這篇文章主要介紹了使用shell腳本采集系統(tǒng)cpu、內(nèi)存、磁盤、網(wǎng)絡(luò)等信息,需要的朋友可以參考下2014-05-05