Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux Shell 動態產生數列 seq 使用技巧與效能優化實戰

編輯:Linux 教學

題目:計算 1..1000 所有偶數之和

方法一:while 迴圈

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

方法二:for 迴圈 + seq(程式碼更簡潔、效能更佳)

start=0; total=0
for i in $(seq $start 2 1000); do
    total=$(($total+$i))
done
echo $total   # 250500

效能比較

$ time (start=0; total=0; for i in $(seq $start 2 1000); do total=$(($total+$i)); done; echo $total)
real 0m0.016s

$ time (start=1; total=0; while [ $start -le 1000 ]; do [[ $(($start%2)) == 0 ]] && total=$(($total+$start)); start=$(($start+1)); done; echo $total)
real 0m0.073s

方法一耗時是方法二的 6 倍!

seq 使用語法

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

範例

seq 1000              # 1 2 3 ... 1000
seq 2 1000            # 2 3 4 ... 1000
seq 1 3 10            # 1 4 7 10(起始 1,遞增 3,至 10)

自訂分隔符

seq -s'#' 1 3 10
1#4#7#10

進階應用技巧

1. 產生連續陣列

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

2. 產生連續相同字元

seq -s '#' 30 | sed -e 's/[0-9]*//g'
##############################

原理:指定分隔符 #,再以 sed 移除數字,留下連續 #。撰寫分隔線、進度條極為方便。

Copyright © Windows教程網 All Rights Reserved