这段时间刚在学习shell的脚本命令,今天学到了awk这个命令,前段时间由于工作原因,深感shell知识匮乏,在工作中用到的最多的命令之一,便是awk,当然grep也是不少。
今天小试了下写了个简单的awk脚本但一直通不过。异常如下:
belts.awk: BEGIN{FS=#: not found.
belts.awk[2]: belt[Yellow]: not found.
belts.awk[3]: belt[Orange]: not found.
belts.awk[4]: belt[Red]: not found.
belts.awk[5]: student[Junior]: not found.
belts.awk[6]: student[Senior]}: not found.
belts.awk[7]: Syntax error at line 7 : `(' is not expected.
老是说这些东西找不到。弄到最后,竟然悲剧的发现,是脚本中少了#!/bin/awk -f这句话。
在调用.awk文件的时候必须指明当前的路径,否则shell会在预定义的变量中去寻找XX.awk,所以会出现
command not found这样的报错。
下面就把脚本和执行结果贴出来,大家共同学习
首先建立一个文本文件myfile
Yellow#Junior
Orange#Junior
Yellow#Senior
Purple#Junior
Brown-2#Junior
White#Senior
Orange#Senior
Red#Junior
Brown-2#Senior
Yellow#Senior
Red#Junior
Blue#Senior
Green#Senior
Purple#Junior
White#Junior
建立一个awk脚本文件belts.awk
建立文件命令:touch belts.awk
给文件赋可执行权限:chmod u+x belts.awk 或 chmod 744 belts.awk
内容如下:
#!/bin/awk -f
BEGIN{FS="#"
belt["Yellow"]
belt["Orange"]
belt["Red"]
student["Junior"]
student["Senior"]}
{for (color in belt)
{if($1==color)
belt[color]++}}
{for (senior_or in student){
if($2==senior_or)
student[senior_or]++}}
END{for (color in belt)print "The club has ",belt[color],color,"Belts"
for(senior_or in student)print "The club has ",
student[senior_or]\
,senior_or,"student"}
上述任务首先在BEGIN中定义了一些数组前三个数组名相同,后两个相同。前三个是统计上面myfile文件中的第一个字段,统计学员分别为黄段,橘段和红段的人数,后面两个同名数组是统计学员中成年人和未成年人的人数。
END部分则输出统计结果。执行脚本命令:belts.awk myfile
The club has 2 Orange Belts
The club has 2 Red Belts
The club has 3 Yellow Belts
The club has 8 Junior student
The club has 7 Senior student
结果就出来了。