Bash腳本編程之數組

聲明數組

declare -a array_name數組

數組初始賦值

  • array_name[xx]=value
    其中xx表示下標,爲大於等於0的整數數字
  • array_name=([xx]=value1 [yy]=value2 ...)
    其中xx表示下標,爲大於等於0的整數數字
  • array_name=(value1 value2 value3 ...)declare -a array_name=(value1 value2 value3 ...)

數組追加元素

array=( "${array[@]}" "new element" )array[${#array[*]}]="new element"函數

複製數組

array2=( "${array1[@]}" )array2="${array1[@]}"code

獲取單個、所有或連續的部分數組元素

  • ${array_name[xx]}
    獲取下標爲xx的單個元素
  • ${array_name[@]}${array_name[*]}
    獲取全部元素。在有引號括起的狀況下,"${array_name[@]}"表示單獨的數組元素,"${array_name[*]}"表示數組元素總體,沒有引號括起的狀況下都表示單獨的數組元素,相似$*$@的區別
  • ${array_name[@]:index:length}
    獲取連續的部分數組元素,其中:length可省略。three

    arrayZ=( one two three four five )
    
    # 提取全部元素
    echo ${arrayZ[@]:0}     # one two three four five
    # 提取下標從1開始(包含)的全部元素
    echo ${arrayZ[@]:1}     # two three four five
    # 提取下標從1開始(包含)的2個元素
    echo ${arrayZ[@]:1:2}   # two three

獲取數組元素個數

${#array_name[*]}${#array_name[@]}element

獲取數組某個元素的字符串長度

${#array_name[xx]}字符串

提取數組中某個元素的部分字符串

${array_name[xx]:index:length}, 其中:length可省略co

刪除數組或數組元素

  • unset array_name[xx]
    刪除下標爲xx的數組元素,等同於array_name[xx]=
  • unset array_name
    刪除整個數組

數組元素的字符串替換/刪除操做

一般狀況下,形如${name...}表示法的字符串操做均可以應用在數組上,使用${name[@]...}${name[*]...}的方式。字符

  • 子字符串移除數字

    arrayZ=( one two three four five five )
    
    # 從每一個元素的最左側進行最短匹配,並刪除匹配的字符串
    echo ${arrayZ[@]#fiv}   # one two three four e e
    echo ${arrayZ[@]#t*e}   # one two e four five five
    
    # 從每一個元素的最左側進行最長匹配,並刪除匹配的字符串
    echo ${arrayZ[@]##t*e}  # one two four five five
    
    # 從每一個元素的最右側進行最短匹配,並刪除匹配的字符串
    echo ${arrayZ[@]%h*e}   # one two t four five five
    
    # 從每一個元素的最右側進行最長匹配,並刪除匹配的字符串
    echo ${arrayZ[@]%%t*e}  # one two four five five
  • 子字符串替換new

    arrayZ=( one two three four fivefive fivefive )
    
    # 對每一個元素進行字符串匹配,並替換第一次匹配的字符串
    echo ${arrayZ[@]/fiv/XYZ}   # one two three four XYZefive XYZefive
    
    # 對每一個元素進行字符串匹配,並替換全部匹配的字符串
    echo ${arrayZ[@]//fiv/XYZ}  # one two three four XYZeXYZe XYZeXYZe
    
    # 對每一個元素進行字符串匹配,並刪除全部匹配的字符串
    echo ${arrayZ[@]//fi/}      # one two three four veve veve
    
    # 從每一個元素的最左側進行最長匹配,並替換匹配的字符串
    echo ${arrayZ[@]/#f*v/XYZ}  # one two three four XYZe XYZe
    
    # 從每一個元素的最右側進行最長匹配,並替換匹配的字符串
    echo ${arrayZ[@]/%i*e/XYZ}  # one two three four fXYZ fXYZ
    
    # 其餘用法:函數的標準輸出做爲要替換的字符串
    replacement() {
        echo -n '!!!'
    }
    echo ${arrayZ[@]/%e/$(replacement)} # on!!! two thre!!! four fivefiv!!! fivefiv!!!
相關文章
相關標籤/搜索