BEGIN语句使用在任何文本浏览动作之前,之后文本浏览动作依据输入文件开始执行。单是这样看一头雾水,下面做个实验就清楚啦~~
- [root@demo ~]# cat awk1.t
- reed 100 90 100 1
- deer 99 91 99 2
- hjl 92 100 80 3
- gsl 80 80 80 5
- zww 85 85 85 4
- [root@demo ~]# awk '{print "name\tthe 2nd number\n----------------"}{print $1"\t"$2}' awk1.t
- name the 2nd number
- ----------------
- reed 100
- name the 2nd number
- ----------------
- deer 99
- name the 2nd number
- ----------------
- hjl 92
- name the 2nd number
- ----------------
- gsl 80
- name the 2nd number
- ----------------
- zww 85
- [root@demo ~]# awk 'BEGIN{print "name\tthe 2nd number\n----------------"}{print $1"\t"$2}' awk1.t
- name the 2nd number
- ----------------
- reed 100
- deer 99
- hjl 92
- gsl 80
- zww 85
END语句用来在a w k完成文本浏览动作后打印输出文本总数和结尾状态标志。
- [root@demo ~]# awk 'BEGIN{print "2nd\t3rd\n----------------"}{a+=$2}{b+=$3}{print a"\t"b}' awk1.t
- 2nd 3rd
- ----------------
- 100 90
- 199 181
- 291 281
- 371 361
- 456 446
- [root@demo ~]# awk 'BEGIN{print "2nd\t3rd\n----------------"}{a+=$2}{b+=$3}END{print a"\t"b}' awk1.t
- 2nd 3rd
- ----------------
- 456 446
- [root@demo ~]#
有例子看就很明白啦~~