国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 服務器 > Web服務器 > 正文

Shell 數組與關聯數組詳解及實例代碼

2024-09-01 13:50:26
字體:
來源:轉載
供稿:網友

Shell 數組與關聯數組

1.數組

1.1. 數組定義

一對圓括號表示數組,數組元素之間用空格符號分割

xiaosi@Qunar:~$ a=(1 2 3)xiaosi@Qunar:~$ echo $a1xiaosi@Qunar:~$ a=("yoona" "lucy" "tom")xiaosi@Qunar:~$ echo $ayoona

1.2. 數組長度,元素,賦值與刪除

長度:用${#數組名[@或*]} 可以得到數組長度

xiaosi@Qunar:~$ echo ${#a[@]}3xiaosi@Qunar:~$ echo ${#a[*]}3

獲取元素:用${數組名[下標]} 得到數組元素(下標從0開始), 下標為*或者@得到整個數組內容

xiaosi@Qunar:~$ array=("yoona" "lucy" "tom")xiaosi@Qunar:~$ echo ${array[0]}yoonaxiaosi@Qunar:~$ echo ${array[1]}lucyxiaosi@Qunar:~$ echo ${array[*]}yoona lucy tomxiaosi@Qunar:~$ echo ${array[@]}yoona lucy tom

賦值:通過數組名[下標]可以對其進行引用賦值,如果下標不存在,自動添加新一個數組元素

xiaosi@Qunar:~$ array=("yoona" "lucy" "tom")xiaosi@Qunar:~$ echo ${array[2]}tomxiaosi@Qunar:~$ array[2]=lilyxiaosi@Qunar:~$ echo ${array[2]}lily

刪除:通過unset數組[下標]可以清除相應的元素,不帶下標則清除全部數據

xiaosi@Qunar:~$ array=("yoona" "lucy" "tom")xiaosi@Qunar:~$ unset array[1]xiaosi@Qunar:~$ echo ${array[*]}yoona tomxiaosi@Qunar:~$ unset arrayxiaosi@Qunar:~$ echo ${array[*]}xiaosi@Qunar:~$ 

1.3. 獲取某范圍的元素

直接通過 ${數組名[@或*]:起始位置:長度} 獲取數組給定范圍內元素,返回字符串,中間用空格分開

xiaosi@Qunar:~$ array=(yoona lucy tom)xiaosi@Qunar:~$ echo ${array[*]}yoona lucy tomxiaosi@Qunar:~$ echo ${array[*]:1:2}lucy tomxiaosi@Qunar:~$ echo ${array[@]:0:1}yoona

1.4. 替換

${數組名[@或*]/查找字符/替換字符} 該操作不會改變原先數組內容,如果需要修改,可以看上面例子

xiaosi@Qunar:~$ array=(yoona lucy tom)xiaosi@Qunar:~$ echo ${array[@]/lucy/lily}yoona lily tomxiaosi@Qunar:~$ echo ${array[@]}yoona lucy tom

2. 關聯數組

Bash支持關聯數組,它可以使用字符串作為數組索引,有時候采用字符串索引更容易理解。

2.1 定義關聯數組

首先需要使用聲明語句將一個變量聲明為關聯數組。

xiaosi@Qunar:~$ declare -A assArray

聲明之后,可以有兩種方法將元素添加到關聯數組中。

(1)利用內嵌索引-值列表的方法

xiaosi@Qunar:~$ assArray=([lucy]=beijing [yoona]=shanghai)xiaosi@Qunar:~$ echo ${assArray[lucy]}beijing

(2)使用獨立的索引-值進行賦值

xiaosi@Qunar:~$ assArray[lily]=shandongxiaosi@Qunar:~$ assArray[sunny]=xianxiaosi@Qunar:~$ echo ${assArray[sunny]}xianxiaosi@Qunar:~$ echo ${assArray[lily]}shandong

2.2 列出數組索引

每一個數組都有一個索引用于查找。使用${!數組名[@或者*]}獲取數組的索引列表

xiaosi@Qunar:~$ echo ${!assArray[*]}lily yoona sunny lucyxiaosi@Qunar:~$ echo ${!assArray[@]}lily yoona sunny lucy

?2.3 獲取所有鍵值對

#! /bin/bashdeclare -A cityArraycityArray=([yoona]=beijing [lucy]=shanghai [lily]=shandong)for key in ${!cityArray[*]}do echo "${key} come from ${cityArray[$key]}"done

?結果:

xiaosi@Qunar:~/company/sh$ bash array.sh lily come from shandongyoona come from beijinglucy come from shanghai

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 湖南省| 兴和县| 精河县| 衡阳县| 长丰县| 建昌县| 南漳县| 肥东县| 水城县| 循化| 霍州市| 平乡县| 佛山市| 红河县| 盐池县| 宣化县| 彩票| 临漳县| 南宫市| 贺州市| 上杭县| 浑源县| 彭州市| 商水县| 工布江达县| 开封县| 曲阳县| 五河县| 三明市| 都匀市| 黔东| 永嘉县| 桃源县| 元阳县| 望城县| 秦皇岛市| 珠海市| 保靖县| 容城县| 凤阳县| 石棉县|