一、awk脚本定义格式
格式1:
BEGIN{} pattern{} END{}
格式2:
#!/bin/awk -f
#add 'x' right
BEGIN{} pattern{} END{}
awk [-v var=value] f1.awk [file]
f2.awk [-v var=value] [var1=value1] [file]
二、脚本示例
? ? ? ? 示例1
[root@localhost ~]# vim f2.awk
#!/bin/awk -f
{if($3>=1000)print $1,$3}
[root@localhost ~]# awk -F: -f f2.awk /etc/passwd
tom 1000
jack 1001
Tom 1002
Jack 1004
opp 1008
abc 1009
qian 1010
yoa 1011
huang 1012
kai 1013
kong 1014
cai 1015
duo 1016
gou 1017
ji 1018
liangl 1019
han 1020
?
?
? ? ? ? 示例2
[root@localhost ~]# vim score.txt #1、创建一个文件(学生成绩表)
Marry 2143 78 84 77
Jack 2321 66 78 45
Tom 2122 48 77 71
Mike 2537 87 97 95
Bob 2415 40 57 62
[root@localhost ~]# vim cal.awk #2、定义 awk 脚本
#!/bin/awk -f
#运行前
BEGIN {
math =0
english =0
computer =0
printf "NAME NO. MATH ENFLISH COMPUTER TOTAL\n"
printf "----------------------------------------------\n"
}
#运行中
{
math+=$3
english+=$4
computer+=$5
printf "%-6s %-6s %4d %8d %8d %8d\n",$1,$2,$3,$4,$5,$3+$4+$5
}
#运行后
END {
printf "----------------------------------------------\n"
printf" TOTAL:%10d %8d %8d \n", math,english,computer
printf"AVERAGE:%10.2f %8.2f %8.2f\n", math/NR, english/NR, computer/NR
}
[root@localhost ~]# awk -f cal.awk score.txt #执行脚本
NAME NO. MATH ENFLISH COMPUTER TOTAL
-----------------------------------------------
Marry 2143 78 84 77 239
Jack 2321 66 78 45 189
Tom 2122 48 77 71 196
Mike 2537 87 97 95 279
Bob 2415 40 57 62 159
-----------------------------------------------
TOTAL: 319 393 350
AVERAGE: 63.80 78.60 70.00
?
?
?
?
?
?