Linux Shell 數組

 數組的聲明:

  1. 1)array[key]=value # array[0]=one,array[1]=two
複製代碼
  1. 2)declare -a array # array被當作數組名
複製代碼
  1. 3)array=( value1 value2 value3 ... )
複製代碼
  1. 4)array=( [1]=one [2]=two [3]=three ... )
複製代碼
  1. 5)array="one two three" # echo ${array[0|@|*]},把array變量當作數組來處理,但數組元素只有字符串本身
複製代碼

數組的訪問:

  1. 1)${array[key]} # ${array[1]}
複製代碼

數組的刪除

  1. 1)unset array[1] # 刪除數組中第一個元素
複製代碼
  1. 2)unset array # 刪除整個數組
複製代碼

計算數組的長度:

  1. 1)${#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

子串刪除

  1. [root@localhost dev]# echo ${array[@]:0}
  2. one two three four
複製代碼
  1. [root@localhost dev]# echo ${array[@]#t*e} # 左邊開始最短的匹配:"t*e",這將匹配到"thre"
  2. one two e four
複製代碼
  1. [root@localhost dev]# echo ${array[@]##t*e} # 左邊開始最長的匹配,這將匹配到"three"
複製代碼
  1. [root@localhost dev]# array=( [0]=one [1]=two [2]=three [3]=four )
複製代碼
  1. [root@localhost dev]# echo ${array[@] %o} # 從字符串的結尾開始最短的匹配
  2. one tw three four
複製代碼
  1. [root@localhost dev]# echo ${array[@] %%o} # 從字符串的結尾開始最長的匹配
  2. one tw three four
複製代碼

子串替換

  1. [root@localhost dev]# array=( [0]=one [1]=two [2]=three [3]=four )
複製代碼

第一個匹配到的,會被刪除

  1. [root@localhost dev]# echo ${array[@] /o/m}
  2. mne twm three fmur
複製代碼

所有匹配到的,都會被刪除

  1. [root@localhost dev]# echo ${array[@] //o/m}
  2. mne twm three fmur
複製代碼

沒有指定替換子串,則刪除匹配到的子符

  1. [root@localhost dev]# echo ${array[@] //o/}
  2. ne tw three fur
複製代碼

替換字符串前端子串

  1. [root@localhost dev]# echo ${array[@] /#o/k}
  2. kne two three four
複製代碼

替換字符串後端子串

 

  1. [root@localhost dev]# echo ${array[@] /%o/k}
  2. 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))})
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章