bash shell数组模拟队列queue和shell数组使用技巧
?
一 shell數(shù)組操作模擬隊(duì)列queue或者棧stack
http://www.tech-recipes.com/rx/911/queue-and-stack-using-array/
here is a series of operation on array,we can use these functions to implement a queue or stack that can help us more
push:
array=(“${array[@]}” $new_element)
pop:
array=(${array[@]:0:$((${#array[@]}-1))})
?
shift:
array=(${array[@]:1})
unshift
array=($new_element “${array[@]}”)
?
function del_array {
local i
for (( i = 0 ; i < ${#array[@]} ; i++ ))
do
if [ "$1" = "${array[$i]}" ] ;then
break
fi
done
del_array_index $i
}
?
function del_array_index {
array=(${array[@]:0:$1} ${array[@]:$(($1 + 1))})
}
?
二 創(chuàng)建shell數(shù)組及使用技巧
轉(zhuǎn)載:http://www.cnblogs.com/chengmo/archive/2010/09/30/1839632.html
在數(shù)組方面一些操作進(jìn)行的總結(jié)。
1.數(shù)組定義
?
[chengmo@centos5 ~]$ a=(1 2 3 4 5)
[chengmo@centos5 ~]$ echo $a
1
?
一對(duì)括號(hào)表示是數(shù)組,數(shù)組元素用“空格”符號(hào)分割開。
?
2.數(shù)組讀取與賦值
- 得到長度:
[chengmo@centos5 ~]$ echo ${#a[@]}
5
用${#數(shù)組名[@或*]} 可以得到數(shù)組長度
- 讀取:
[chengmo@centos5 ~]$ echo ${a[2]}
3
[chengmo@centos5 ~]$ echo ${a[*]}
1 2 3 4 5???
用${數(shù)組名[下標(biāo)]} 下標(biāo)是從0開始? 下標(biāo)是:*或者@ 得到整個(gè)數(shù)組內(nèi)容
- 賦值:
[chengmo@centos5 ~]$ a[1]=100
[chengmo@centos5 ~]$ echo ${a[*]}
1 100 3 4 5
?
[chengmo@centos5 ~]$ a[5]=100????
[chengmo@centos5 ~]$ echo ${a[*]}
1 100 3 4 5 100
直接通過 數(shù)組名[下標(biāo)] 就可以對(duì)其進(jìn)行引用賦值,如果下標(biāo)不存在,自動(dòng)添加新一個(gè)數(shù)組元素
- 刪除:
[chengmo@centos5 ~]$ a=(1 2 3 4 5)
[chengmo@centos5 ~]$ unset a
[chengmo@centos5 ~]$ echo ${a[*]}
[chengmo@centos5 ~]$ a=(1 2 3 4 5)
[chengmo@centos5 ~]$ unset a[1]??
[chengmo@centos5 ~]$ echo ${a[*]}
1 3 4 5
[chengmo@centos5 ~]$ echo ${#a[*]}
4
直接通過:unset 數(shù)組[下標(biāo)] 可以清除相應(yīng)的元素,不帶下標(biāo),清除整個(gè)數(shù)據(jù)。
?
?
3.特殊使用
- 分片:
[chengmo@centos5 ~]$ a=(1 2 3 4 5)
[chengmo@centos5 ~]$ echo ${a[@]:0:3}
1 2 3
[chengmo@centos5 ~]$ echo ${a[@]:1:4}
2 3 4 5
[chengmo@centos5 ~]$ c=(${a[@]:1:4})
[chengmo@centos5 ~]$ echo ${#c[@]}
4
[chengmo@centos5 ~]$ echo ${c[*]}
2 3 4 5
直接通過 ${數(shù)組名[@或*]:起始位置:長度} 切片原先數(shù)組,返回是字符串,中間用“空格”分開,因此如果加上”()”,將得到切片數(shù)組,上面例子:c 就是一個(gè)新數(shù)據(jù)。
- 替換:
[chengmo@centos5 ~]$ a=(1 2 3 4 5)???
[chengmo@centos5 ~]$ echo ${a[@]/3/100}
1 2 100 4 5
[chengmo@centos5 ~]$ echo ${a[@]}
1 2 3 4 5
[chengmo@centos5 ~]$ a=(${a[@]/3/100})
[chengmo@centos5 ~]$ echo ${a[@]}????
1 2 100 4 5
調(diào)用方法是:${數(shù)組名[@或*]/查找字符/替換字符} 該操作不會(huì)改變?cè)葦?shù)組內(nèi)容,如果需要修改,可以看上面例子,重新定義數(shù)據(jù)。
?
從上面講到的,大家可以發(fā)現(xiàn)linux shell 的數(shù)組已經(jīng)很強(qiáng)大了,常見的操作已經(jīng)綽綽有余了。
總結(jié)
以上是生活随笔為你收集整理的bash shell数组模拟队列queue和shell数组使用技巧的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 有些盲人,竟然不知道自己是盲人
- 下一篇: printf and echo