Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2363034
  • 博文数量: 298
  • 博客积分: 7876
  • 博客等级: 准将
  • 技术积分: 5500
  • 用 户 组: 普通用户
  • 注册时间: 2011-02-23 13:39
文章存档

2013年(2)

2012年(142)

2011年(154)

分类: Python/Ruby

2012-04-23 21:18:47

Shell数组

 

整理自:

整理自:http://www.cnblogs.com/chengmo/archive/2010/09/30/1839632.html

 

1. 数组的声明:

1)array[key]=value # array[0]=one,array[1]=two

2)declare -a array # array被当作数组名

3)array=( value1 value2 value3 ... )

4)array=( [1]=one [2]=two [3]=three ... )

5)array="one two three" # echo ${array[0|@|*]},array变量当作数组来处理,但数组元素只有字符串本身

2. 数组的访问:

[oper@here]$ echo ${a[2]}
3

[oper@here]$ echo ${a[*]}
1 2 3 4 5   

${数组名[下标]} 下标是从0开始  下标是:*或者@ 得到整个数组内容

 

3. 数组的删除:

1)unset array[1] # 删除数组中第一个元素

2)unset array # 删除整个数组

4. 数组的长度:

1)${#array} #等同于${#array[*]} ${#array[@]}

2)${#array[0]}#数组第一个元素的长度。

5.分片:

[oper@here]$ a=(1 2 3 4 5)
[oper@here]$ echo ${a[@]:0:3}
1 2 3
[oper@here]$ echo ${a[@]:1:4}
2 3 4 5

[oper@here]$ c=(${a[@]:1:4})
[oper@here]$ echo ${#c[@]}
4
[oper@here]$ echo ${c[*]}
2 3 4 5

直接通过 ${数组名[@*]:起始位置:长度} 切片原先数组,返回是字符串,中间用空格分开,因此如果加上”()”,将得到切片数组,上面例子:c 就是一个新数据。

 

6.子串的删除:

 

[oper@here]# echo ${array[@]:0}

one two three four

[oper@here]# echo ${array[@]#t*e} # 左边开始最短的匹配:"t*e",这将匹配到"thre"(通配符)

one two e four

[oper@here]# echo ${array[@]##t*e} # 左边开始最长的匹配,这将匹配到"three"

[oper@here]# array=( [0]=one [1]=two [2]=three [3]=four )

[oper@here]# echo ${array[@] %o} # 从字符串的结尾开始最短的匹配

one tw three four

[oper@here]# echo ${array[@] %%o} # 从字符串的结尾开始最长的匹配

one tw three four

7.子串的替换:

调用方法是:${数组名[@*]/查找字符/替换字符} 该操作不会改变原先数组内容,如果需要修改,可以看上面例子,重新定义数据。

 

[oper@here]# array=( [0]=one [1]=two [2]=three [3]=four )

所有匹配到的,都会被替换

[oper@here]# echo ${array[@] /o/m}#按照理论来说应该是替换第一个,但是确实全部替换了??

mne twm three fmur

 [oper@here]# echo ${array[@] //o/m}

mne twm three fmur

没有指定替换子串,则删除匹配到的子符

[oper@here]# echo ${array[@] //o/}

ne tw three fur

替换字符串前端子串

[oper@here]# echo ${array[@] /#o/k}

kne two three four

替换字符串后端子串

[oper@here]# echo ${array[@] /%o/k}

one twk three four

 

阅读(2502) | 评论(0) | 转发(0) |
0

上一篇:SSH使用指南

下一篇:Shell中[和[[的异同

给主人留下些什么吧!~~