shell-------------数组

来源:互联网 发布:weui.min.js cdn 编辑:程序博客网 时间:2024/05/22 20:28

先看一个例子:

#!/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-



#子串删除

#从字符串的前部删除最短的匹配,

#+匹配字串是一个正则表达式.

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

#匹配表达式作用于数组所有元素.



原创粉丝点击