Linux Shell 動態(tài)生成 數(shù)組系列 Seq 使用技巧
如果對linux shell 數(shù)組不是很熟悉的話坷襟,請看上一篇文章:Linux Shell 數(shù)組建立及使用技巧 ,這篇文章主要講是動態(tài)生成數(shù)組系列回官。方法應該很多普气,我這里主要以一個求和計算的題目為例進行分析根暑。
題目:請用linux shell 寫一段腳本,實現(xiàn)從1..1000中所有偶數(shù)的和值帆疟。
方法一:
通過while 循環(huán)得到需要的結果:
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
以上運行結果是:249500,在linux shell 中轻要,”;”作為命令行分隔符。如果大家對于$(()) 運算符號不是很理解旱爆,可以查看:linux shell 實現(xiàn) 四則運算(整數(shù)及浮點) 簡單方法 舀射,如果對于:[[]] [] 符號,可以參考另外一篇文章linux shell 邏輯運算符怀伦、邏輯表達式詳解脆烟。
方法二:
通過 for 循環(huán)得到結果:
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ō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
方法一耗時 是方法二的 6倍邢羔!
seq 使用:
seq [OPTION]... LAST
seq [OPTION]... FIRST LAST
seq [OPTION]... FIRST INCREMENT LAST
[chengmo@centos5 ~]$ seq 1000 ‘起始默認是 1,間隔默認也是1
[chengmo@centos5 ~]$seq 2 1000 ‘間隔默認是1
[chengmo@centos5 ~]$seq 1 3 10 '從1開始桑孩,到10 間隔為3 結果是:1 4 7 10
說明:默認間隔是“空格” 如果想換成其它的可以帶參數(shù):-s
[chengmo@centos5 ~]$seq -s'#' 1 3 10
1#4#7#10
應用技巧:
生成連續(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'
#############################
上面例子:通過加入間隔字符‘0莺祝’后,替換掉數(shù)字洼怔, 生成連續(xù)相同字符’#’署惯,這個在以后書寫中還是有不少幫助。