shell脚本编程实例--进度条,求和&平均值,斐波那契,改变字符串大小顺序
Posted xy913741894
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了shell脚本编程实例--进度条,求和&平均值,斐波那契,改变字符串大小顺序相关的知识,希望对你有一定的参考价值。
利用求1+2+3+…+100的和,要求打印出1+2+3+…+100=5050
我想了两种方法:
- 字符串拼接
- 依次打印
两种思路代码如下:
//依次打印
sum=0
for ((i=1; i<=100; i++))
do
if [ $i -eq 100 ];then
echo -n "$i="
break
fi
echo -n "$i+"
let sum+=i
done
echo $sum
//字符串拼接
sum=0
i=1
str=""
while test $i -le 100
do
if [ $i -eq 100 ];then
str=$str$i"="
break
fi
str=$str$i"+"
let sum+=i
let i++
done
echo $str$sum
利用函数实现三个数的最大值,三个数需要从命令行传入
function max_min()
max=$1
min=$1
for i in $@
do
if test $max -lt $i ;then
max=$i
fi
if [ $min -gt $i ]; then
min=$i
fi
done
echo "max = $max"
echo "min = $min"
max_min $1 $2 $3
显示进度条
str=''
arr=( "|" "/" "-" "\\\\")
count=0
for ((i=0; i<=100; i++))
do
printf "[%-100s][%d%%][%c]\\r" "$str" "$i" "$arr[count]"
str=$str'#'
let count++
let count%=4
sleep 0.05
done
#echo ""
printf "\\n"
彩色进度条
function f()
local color='\\033[45m'
local clear='\\033[0m'
str=''
arr=( "|" "/" "-" "\\\\")
count=0
for ((i=0; i<=100; i++))
do
printf "$color[%s][%d%%][%c]$clear\\r" "$str" "$i" "$arr[count]"
str=$str' '
let count++
let count%=4
sleep 0.05
done
#echo ""
printf "\\n"
f #调用函数
斐波那契
说明:为了尽快熟悉shell语法,Fib采用三种方法实现
function Fib()
local first=1
local second=1
local third=$(( $first+$second ))
if [ $1 -le 0 ];then
echo "$1 should be > 0"
exit -1
elif [ $1 -eq 1 -o $1 -eq 2 ];then
echo 1
exit 0
fi
i=3
while [ $i -le $1 ]
do
let third=first+second
let first=second
let second=third
let i++
done
echo $third
function FibArr()
local arr=()
arr[1]=1
arr[2]=1
if [ $1 -le 0 ];then
echo "$1 should be > 0"
exit -1
elif [ $1 -eq 1 -o $1 -eq 2 ];then
echo 1
exit 0
fi
i=3
while test $i -le $1
do
let arr[i]=arr[i-1]+arr[i-2]
let i++
done
echo $arr[$1]
function FibR()
if [ $1 -eq 1 -o $1 -eq 2 ];then
echo 1
exit 0
fi
pprev=$(( $1-2 ))
prev=$(( $1-1 ))
pprev_ret=$(FibR $pprev)
prev_ret=$(FibR $prev)
ret=$(( pprev_ret+prev_ret ))
echo $ret
FibR $1
Fib $1
FibArr $1
求平均值,精度保证两位小数
if [ $# -lt 3 ];then
echo "please input at least 3 arg"
exit -1
fi
max=$1
min=$1
sum=0
for i in $@
do
#if [ $max -lt $i ];then
# max=$i
#fi
#if [ $min -gt $i ];then
# min=$i
#fi
[ $max -lt $i ] && max=$i
[ $min -gt $i ] && min=$i
let sum+=i
done
echo "max=$max"
echo "min=$min"
echo "sum=$sum"
avg=` echo "scale=2; $sum / $#" | bc`
echo "avg=$avg"
改变字符串
123abc456
123def456改为
123ABC456
123DEF456
while read line
do
part1=` echo $line | cut -c 1-3 `
part2=` echo $line | cut -c 4-6 | tr '[a-z]' '[A-Z]' `
part3=` echo $line | cut -c 7-9 `
echo $part3$part2$part1
done < file > newfile
以上是关于shell脚本编程实例--进度条,求和&平均值,斐波那契,改变字符串大小顺序的主要内容,如果未能解决你的问题,请参考以下文章