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

先看一个例子:

#!/bin/bash

area2=(zero one two three four)

echo "Origin is :"
echo ${area2[0]} ${area2[1]} ${area2[2]} ${area2[3]} ${area2[4]}

area2[1]=1
area2[4]=4
echo "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/bash

area2=(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

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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值