欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Shell動(dòng)態(tài)生成數(shù)組的多種方法

 更新時(shí)間:2015年07月09日 09:10:32   投稿:junjie  
這篇文章主要介紹了Shell動(dòng)態(tài)生成數(shù)組的多種方法,本文給出while循環(huán)法和for循環(huán)法,以及使用seq生成數(shù)組法,需要的朋友可以參考下

如果對(duì)linux shell 數(shù)組不是很熟悉的話,請(qǐng)看上一篇文章:linux shell 數(shù)組建立及使用技巧  ,這篇文章主要講是動(dòng)態(tài)生成數(shù)組系列。方法應(yīng)該很多,我這里主要以一個(gè)求和計(jì)算的題目為例進(jìn)行分析。

 

題目:請(qǐng)用linux shell 寫一段腳本,實(shí)現(xiàn)從1..1000中所有偶數(shù)的和值。

 

方法一:

通過(guò)while 循環(huán)得到需要的結(jié)果:

start=1;

total=0;

while [ $start -le 1000 ];do

  [[ $(($start%2)) == 0 ]]&&total=$(($total+$start));

  start=$(($start+1));

done;

echo $total;

 

[chengmo@centos5 ~]$ start=1;total=0;while [ $start -le 1000 ];do  [[ $(($start%2)) == 0 ]]&&total=$(($total+$start));  start=$(($start+1));done;echo $total;
250500

以上運(yùn)行結(jié)果是:249500,在linux shell 中,”;”作為命令行分隔符。如果大家對(duì)于$(()) 運(yùn)算符號(hào)不是很理解,可以查看:linux shell 實(shí)現(xiàn) 四則運(yùn)算(整數(shù)及浮點(diǎn)) 簡(jiǎn)單方法  ,如果對(duì)于:[[]] [] 符號(hào),可以參考另外一篇文章linux shell 邏輯運(yùn)算符、邏輯表達(dá)式詳解。


方法二:

通過(guò) for 循環(huán)得到結(jié)果:

start=0;

total=0;

for i in $(seq $start 2 1000); do

  total=$(($total+$i));

done;

echo $total;

[chengmo@centos5 ~]$ start=0;total=0;for i in $(seq $start 2 1000); do  total=$(($total+$i));done;echo $total;    
250500

 

上面語(yǔ)句已經(jīng)代碼方面明顯優(yōu)于方法一,而且性能方面表現(xiàn)也很好。下面比較就可以發(fā)現(xiàn):

 

 

比較性能:

[chengmo@centos5 ~]$ time (start=0;total=0;for i in $(seq $start 2 1000); do  total=$(($total+$i));done;echo $total;)       250500

real  0m0.016s
user  0m0.012s
sys   0m0.003s
[chengmo@centos5 ~]$ time (start=1;total=0;while [ $start -le 1000 ];do  [[ $(($start%2)) == 0 ]]&&total=$(($total+$start));  start=$(($start+1));done;echo $total;) 
250500

real  0m0.073s
user  0m0.069s
sys   0m0.004s

方法一耗時(shí) 是方法二的 6倍!


seq 使用:

seq [OPTION]... LAST
seq [OPTION]... FIRST LAST
seq [OPTION]... FIRST INCREMENT LAST

[chengmo@centos5 ~]$ seq 1000  ‘起始默認(rèn)是 1,間隔默認(rèn)也是1

[chengmo@centos5 ~]$seq 2 1000 ‘間隔默認(rèn)是1

[chengmo@centos5 ~]$seq 1 3 10  '從1開始,到10 間隔為3 結(jié)果是:1 4 7 10

說(shuō)明:默認(rèn)間隔是“空格” 如果想換成其它的可以帶參數(shù):-s

[chengmo@centos5 ~]$seq -s'#' 1 3 10

1#4#7#10

 

應(yīng)用技巧:

 
生成連續(xù)數(shù)組系列:

 

[chengmo@centos5 ~]$ a=($(seq 1 3 10))  
[chengmo@centos5 ~]$ echo ${a[1]}
4
[chengmo@centos5 ~]$ echo ${a[@]}
1 4 7 10

 
生成連續(xù)相同字符:

[chengmo@centos5 ~]$ seq -s '#' 30 | sed -e 's/[0-9]*//g'
#############################

上面例子:通過(guò)加入間隔字符‘#'后,替換掉數(shù)字, 生成連續(xù)相同字符'#',這個(gè)在以后書寫中還是有不少幫助。

相關(guān)文章

最新評(píng)論