码迷,mamicode.com
首页 > 编程语言 > 详细

linux shell之数组的特殊用法

时间:2021-04-13 12:08:59      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:his   input   declare   from   use   两条命令   pac   操作   removing   


vi string_array.sh
#!/bin/bash

city=(Nanjing Atlanta Massachusetts Marseilles) #建立一个简单的数组
echo "Extracting Substring" #演示抽取子串功能
echo ${city[*]:0} #抽取整个数组
echo ${city[*]:1} #抽取从第1个元素到结束的数组
echo ${city[*]:3} #抽取从第3个元素到结束的数组
echo ${city[*]:0:2} #抽取从第0个元素开始的2个元素

echo
echo "Removing Substring" #演示删除子串功能
echo ${city[*]#M*a} #删除从M到a的最短子串
echo ${city[*]##M*a} #删除从M到工的最长子串
echo

echo "Replacing Substring" #演示替换子串功能
echo "${city[*]/M*s/Year}" #替换第1次与M*s匹配的子串
echo "${city[*]//M*s/Year}" #替换所有与M*s匹配的子串

./string_array.sh
Extracting Substring
Nanjing Atlanta Massachusetts Marseilles
Atlanta Massachusetts Marseilles
Marseilles
Nanjing Atlanta

Removing Substring
Nanjing Atlanta ssachusetts rseilles
Nanjing Atlanta chusetts rseilles

Replacing Substring
Nanjing Atlanta Year Year
Nanjing Atlanta Year Year

注:替换时所得到的结果一样,因为"/"符号第1次匹配子串和"//"符号匹配的全部
子串都是对一个数组元素而言,Massachusetts 和 Marseilles都只有1个与M*s匹配的子串,
所以两条命令得到的结果相同。

arrivedcity.sh脚本演示数组与read命令、unset命令的用法
vi arrivedcity.sh
#!/bin/bash

declare -a arrivedcity #将arrivedcity声明为数组

echo "What city have you been arrived?"
echo "The input Should be seperated from echo other by a SPACE"
read -a arrivedcity
echo

#for循环输出数组的全部内容
for i in "${arrivedcity[@]}"
do
echo $i
done

echo "The length of this array is ${#arrivedcity[@]}."
echo "Executing UNSET operation......"
unset arrivedcity[1] #清空arrivedcity[1]元素
echo "The length of this array is ${#arrivedcity[@]}."
echo "Executing UNSET operation......"
unset arrivedcity
echo "The length of this array is ${#arrivedcity[@]}."

./arrivedcity.sh
What city have you been arrived?
The input Should be seperated from echo other by a SPACE
Shanghai Dalian Melbourne Suzhou Beijing

Shanghai
Dalian
Melbourne
Suzhou
Beijing
The length of this array is 5.
Executing UNSET operation......
The length of this array is 4.
Executing UNSET operation......
The length of this array is 0.

shell还有一种重要的操作---数组连接

linux shell之数组的特殊用法

标签:his   input   declare   from   use   两条命令   pac   操作   removing   

原文地址:https://www.cnblogs.com/zhudaheng123/p/14648019.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!