數組的聲明:
- 1)array[key]=value # array[0]=one,array[1]=two
複製代碼
- 2)declare -a array # array被當作數組名
複製代碼
- 3)array=( value1 value2 value3 ... )
複製代碼
- 4)array=( [1]=one [2]=two [3]=three ... )
複製代碼
- 5)array="one two three" # echo ${array[0|@|*]},把array變量當作數組來處理,但數組元素只有字符串本身
複製代碼
數組的訪問:
- 1)${array[key]} # ${array[1]}
複製代碼
數組的刪除
- 1)unset array[1] # 刪除數組中第一個元素
複製代碼
計算數組的長度:
- 2)${#array[0]} #同上。 ${#array[*]} 、${#array[@]}。注意同#{array:0}的區別
複製代碼
數組的提取
從尾部開始提取:
array=( [0]=one [1]=two [2]=three [3]=four )
${array[@]:1} # two three four,除掉第一個元素後所有元素,那麼${array[@]:0}表示所有元素
${array[@]:0:2} # one two
${array[@]:1:2} # two three
子串刪除
- [root@localhost dev]# echo ${array[@]:0}
- one two three four
複製代碼
- [root@localhost dev]# echo ${array[@]#t*e} # 左邊開始最短的匹配:"t*e",這將匹配到"thre"
- one two e four
複製代碼
- [root@localhost dev]# echo ${array[@]##t*e} # 左邊開始最長的匹配,這將匹配到"three"
複製代碼
- [root@localhost dev]# array=( [0]=one [1]=two [2]=three [3]=four )
複製代碼
- [root@localhost dev]# echo ${array[@] %o} # 從字符串的結尾開始最短的匹配
- one tw three four
複製代碼
- [root@localhost dev]# echo ${array[@] %%o} # 從字符串的結尾開始最長的匹配
- one tw three four
複製代碼
子串替換
- [root@localhost dev]# array=( [0]=one [1]=two [2]=three [3]=four )
複製代碼
第一個匹配到的,會被刪除
- [root@localhost dev]# echo ${array[@] /o/m}
- mne twm three fmur
複製代碼
所有匹配到的,都會被刪除
- [root@localhost dev]# echo ${array[@] //o/m}
- mne twm three fmur
複製代碼
沒有指定替換子串,則刪除匹配到的子符
- [root@localhost dev]# echo ${array[@] //o/}
- ne tw three fur
複製代碼
替換字符串前端子串
- [root@localhost dev]# echo ${array[@] /#o/k}
- kne two three four
複製代碼
替換字符串後端子串
- [root@localhost dev]# echo ${array[@] /%o/k}
- one twk three four
複製代碼
push:
array=(”${array[@]}” $new_element)
pop:
array=(${array[@]:0:$((${#array[@]}-1))})
shift:
array=(${array[@]:1})
unshift
array=($new_element “${array[@]}”)
function del_array {
local i
for (( i = 0 ; i < ${#array[@]} ; i++ ))
do
if [ "$1" = "${array[$i]}” ] ;then
break
fi
done
del_array_index $i
}
function del_array_index {
array=(${array[@]:0:$1} ${array[@]:$(($1 + 1))})
}