天天看点

linux shell- while基本结构简单的例子组合应用

  • 基本结构
  • 简单的例子
  • 组合应用
    • while 和find
    • while 和文件
    • 小彩蛋
如果需要在shell 中对很多行的数据进行处理,

while

太合适了

基本结构

while  command   ; do
done
           

简单的例子

从demofile 中读取每一行,然后显示在屏幕上
while read i ; do   #每次处理一行, 将该行内容存储在i 中
   echo "read line: $i"
done <demofile  # 将demofile 内容交友while 处理
           

组合应用

while 和find

#在最近3天的日志中查找包含错误的日志
  find ./log -atime - -type f | while read i; do
       #只输出exception的文件
       grep "exception" $i && echo "foundfile $i";
  done 

  #统计最近三天日志文件中订单数目
  find ./log -atime - -type f | while read i; do
       #只输出exception的文件
       printf "file: $i, order count: ";
       grep "submitorder" $i |wc -l ;
       echo ;
  done 
           

while 和文件

#输出文件中大于200个字符的行
#写法1
cat filedemo | while read i;do
   //数i这个字符串存了多少个字符
   charcount=`echo $i |wc -c `
   if [ "$charcount" >  ]; then
       print $i
   fi
done

#写法2
while read i;do
   //数i这个字符串存了多少个字符
   charcount=`echo $i |wc -c `
   if [ "$charcount" >  ]; then
       print $i
   fi
done < filedemo
           

小彩蛋

#猜猜是个什么
while :; do :; done




#":"在shell 里也是个命令
           

继续阅读