1.shell实现斐波那契数列
##实现一
arr[0]=1
arr[1]=1
i=0
read max
while [ $i -le $max ]
do
let arr[$i+2]=arr[$i+1]+arr[$i]
let i++
done
echo ${arr[$max]}
#实现二
function fib()
{
temp=$1
if [ $temp -lt 2 ] ;then
echo 1
return
fi
res1=`fib $((temp-1))`
res2=`fib $((temp-2))`
echo $((res1+res2))
}
#read num
#fib $num
#实现三
first=1
second=1
last=1
if [ $1 -lt 2 ];then
echo 1
fi
i=2
while [ $i -le $1 ]
do
let last=$first+$second
let first=$second
let second=$last
let i++
done
echo $last
123abc456
456def123
567abc789
789def567
要求输出:
456ABC123
123DEF456
789ABC567
567DEF789
实现思路:按行读取,将一行切割成三部分,
第二部分字母转化为小写转化为大写
最后拼接成一块输出重定向到另一个文件
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 < file1 >file2
3.用Shell实现希尔排序
function shell_sort()
{
echo ${a[*]}
size=${#a[@]}
gap=$size
#for (( gap=size/3+1;$gap>1; gap=$gap/3+1 ))
while((gap>1))
do
let gap=$gap/3+1
for ((idx=gap;idx<size;idx++))
do
let pre=idx-gap
let save=${a[idx]}
#while [ $pre -ge 0 && $save -le ${a[$pre]} ]
while ((pre>=0&&a[pre]>save))
do
let a[pre+gap]=a[pre]
let pre-=gap
done
let a[$pre+gap]=$save
echo ${a[*]}
done
done
echo ${a[@]}
}
echo "please input num"
read num
i=0
while [ $num -gt 0 ]
do
read a[i]
let i++
let num-=1
echo ${a[*]}
done
shell_sort $@
原文链接:https://www.f2er.com/bash/391569.html