先看一個例子:
#!/bin/basharea2=(zero one two three four)echo "Origin is :"echo ${area2[0]} ${area2[1]} ${area2[2]} ${area2[3]} ${area2[4]}area2[1]=1area2[4]=4echo "After is :"echo ${area2[0]} ${area2[1]} ${area2[2]} ${area2[3]} ${area2[4]}echo ${#area2}echo "One way to output the array:"echo ${area2[@]}
輸出:
root@vivi-Ideapad-Z460:~# ./myshell.sh
Origin is :
zero one two three four
After is :
zero 1 two three 4
4
One way to output the array:
zero 1 two three 4
root@vivi-Ideapad-Z460:~#
#!/bin/basharea2=(zero one two three four)echo "Origin is :"echo ${area2[@]}echo ${area2[@]:0} # 提取尾部的子串echo ${area2[@]:1}echo ${area2[@]:1:2}
root@vivi-Ideapad-Z460:~# ./myshell.sh
Origin is :
zero one two three four
zero one two three four
one two three four
one two
root@vivi-
#
子串刪除
#
從字串的前部刪除最短的匹配,
#+匹配字串是一個Regex.
echo${arrayZ[@]#f*r} # one two three five five
#
匹配運算式作用於數組所有元素.
#
匹配了"four"並把它刪除.
#字串前部最長的匹配
echo${arrayZ[@]##t*e} # one two four five five
#
匹配運算式作用於數組所有元素.
#
匹配"three"並把它刪除.
#字串尾部的最短匹配
echo${arrayZ[@]%h*e} # one two t four five five
#
匹配運算式作用於數組所有元素.
#
匹配"hree"並把它刪除.
#字串尾部的最長相符
echo${arrayZ[@]%%t*e} # one two four five five
#
匹配運算式作用於數組所有元素.
#
匹配"three"並把它刪除.
#子串替換
#第一個匹配的子串會被替換
echo${arrayZ[@]/fiv/XYZ} # one two three four XYZe XYZe
#
匹配運算式作用於數組所有元素.
#所有匹配的子串會被替換
echo${arrayZ[@]//iv/YY} # one two three four fYYe fYYe
#
匹配運算式作用於數組所有元素.
#刪除所有的匹配子串
#沒有指定代替字串意味著刪除
echo${arrayZ[@]//fi/} # one two three four ve ve
#
匹配運算式作用於數組所有元素.
#替換最前部出現的字串
echo${arrayZ[@]/#fi/XY} # one two three four XYve XYve
#
匹配運算式作用於數組所有元素.
#替換最後部出現的字串
echo${arrayZ[@]/%ve/ZZ} # one two three four fiZZ fiZZ
#
匹配運算式作用於數組所有元素.