shell小脚本
2016-06-29 09:15
337 查看
求1-100的和
a. 非递归
b. 递归
2.求出一个文件中数据的最大值、最小值和平均值,精度为2
3.Fiba. 非递归(循环)
b. 递归
4.将一个文件中每一行的字符串进行转换,例如将“123abc456”转换为“456ABC123”
a. 非递归
1 #!/bin/bash 2 sum=0 3 str="" 4 for i in {1..100} 5 do 6 let sum+=i 7 str+="$i+" 8 done 9 echo ${str%+}=$sum输出结果:
b. 递归
29 function fun_sum() 30 { 31 num=$1 32 sum=0 33 if [ ${num} -le 1 ];then 34 echo 1 35 return 36 fi 37 let num-- 38 let sum=$1+$( fun_sum $num) 39 echo ${sum} 40 } 41 function main() 42 { 43 read n 44 sum=$(fun_sum $n ) 45 echo "${sum}" 46 } 47 main输出结果:
2.求出一个文件中数据的最大值、最小值和平均值,精度为2
1 #!/bin/bash 2 count=0 3 4 while read line 5 do 6 let count++ 7 let sum+=$line 8 if [ $count -eq 1 ];then 9 max=$line 10 min=$line 11 ave=0 12 fi 13 [ $max -lt $line ] && max=$line 14 [ $min -gt $line ] && min=$line 15 done<file 16 echo "max=$max" 17 echo "min=$min" 18 echo "ave=`echo "base=10; scale=2; ${sum}/${count}" | bc`"输出结果:
3.Fiba. 非递归(循环)
1 #!/bin/bash 2 function fib() 3 { 4 n=$1 5 a=1 6 b=1 7 if [ ${n} -eq 1 -o ${n} -eq 2 ];then 8 echo 1 9 return 10 fi 11 while [ ${n} -gt 2 ] 12 do 13 let c=a+b 14 a=$b 15 b=$c 16 let n-- 17 done 18 echo ${c} 19 return 20 } 21 function main() 22 { 23 read n 24 fib $n 25 } 26 main输出结果:
b. 递归
function fib() 24 { 25 n=$1 26 if [ $n -eq 1 -o $n -eq 2 ];then 27 echo 1 28 return 29 fi 30 let n-- 31 val1=$(fib $n) 32 let n-- 33 val2=$(fib $n) 34 let ret=$val1+$val2 35 #ret=$(fib (${n}-1))+$(fib (${n}-2)) //为什么这样不行 36 echo $ret 37 return 38 }输出结果:
4.将一个文件中每一行的字符串进行转换,例如将“123abc456”转换为“456ABC123”
1 #!/bin/bash 2 while read line 3 do 4 # num1=$(echo $line | cut -c -3) #方法一 5 # num2=$(echo $line | cut -c 4-6) 6 # num3=$(echo $line | cut -c 7-) 7 num1=${line:0:3} #方法一 8 num2=${line:3:3} 9 num3=${line:6:3} 10 eval echo "${num3}${num2}${num1} | tr [a-z] [A-Z]" 11 done<file0
相关文章推荐
- android wifi 无线调试
- Android Native 绘图方法
- 运维入门
- 动态清空 nohup 输出文件
- install scrapy with pip and easy_install
- Linux Shell常用技巧
- Shell 脚本编程陷阱
- shell字符串操作详解
- Shell中删除某些文件外所有文件的3个方法
- Ruby中执行Linux shell命令的六种方法详解
- VB使用shell函数打开外部exe程序的实现方法
- Shell编程的一些知识集合
- Shell中的for和while循环详细总结
- 什么是Shell?Shell脚本基础知识详细介绍
- Shell脚本中引用、调用另一个脚本文件的2种方法
- Shell脚本解压rpm软件包
- Linux Shell 数组建立及使用技巧
- Shell脚本实现复制文件到多台服务器的代码分享
- Shell脚本实现批量替换文件内容
- Shell脚本实现的一个简易Web服务器例子分享