awk学习笔记之一BEGIN和END

 BEGIN语句使用在任何文本浏览动作之前,之后文本浏览动作依据输入文件开始执行。单是这样看一头雾水,下面做个实验就清楚啦~~

 

  
  
  
  
  1. [root@demo ~]# cat awk1.t   
  2. reed 100 90 100 1 
  3. deer 99  91  99 2 
  4. hjl  92  100 80 3 
  5. gsl  80  80  80 5 
  6. zww  85  85  85 4 
  7. [root@demo ~]# awk '{print "name\tthe 2nd number\n----------------"}{print $1"\t"$2}' awk1.t 
  8. name    the 2nd number 
  9. ---------------- 
  10. reed    100 
  11. name    the 2nd number 
  12. ---------------- 
  13. deer    99 
  14. name    the 2nd number 
  15. ---------------- 
  16. hjl     92 
  17. name    the 2nd number 
  18. ---------------- 
  19. gsl     80 
  20. name    the 2nd number 
  21. ---------------- 
  22. zww     85 
  23. [root@demo ~]# awk 'BEGIN{print "name\tthe 2nd number\n----------------"}{print $1"\t"$2}' awk1.t 
  24. name    the 2nd number 
  25. ---------------- 
  26. reed    100 
  27. deer    99 
  28. hjl     92 
  29. gsl     80 
  30. zww     85 

 END语句用来在a w k完成文本浏览动作后打印输出文本总数和结尾状态标志。

 

  
  
  
  
  1. [root@demo ~]# awk 'BEGIN{print "2nd\t3rd\n----------------"}{a+=$2}{b+=$3}{print a"\t"b}' awk1.t  
  2. 2nd     3rd 
  3. ---------------- 
  4. 100     90 
  5. 199     181 
  6. 291     281 
  7. 371     361 
  8. 456     446 
  9. [root@demo ~]# awk 'BEGIN{print "2nd\t3rd\n----------------"}{a+=$2}{b+=$3}END{print a"\t"b}' awk1.t  
  10. 2nd     3rd 
  11. ---------------- 
  12. 456     446 
  13. [root@demo ~]#  

有例子看就很明白啦~~

你可能感兴趣的:(awk,end,BEGIN)