Chinaunix

标题: 请教一个AWK的语法问题 [打印本页]

作者: Siete    时间: 2008-10-09 14:20
标题: 请教一个AWK的语法问题
在看《LINUX与UNIX SHELL编程指南》关于AWK一章的时候,有点疑问
在讲解AWK数组的时候有这么个例子:

  1. $vi group_student
  2.       1 yellow#junior
  3.       2 orange#senior
  4.       3 yellow#junior
  5.       4 purple#junior
  6.       5 brown-2#junior
  7.       6 white#senior
  8.       7 orange#senior
  9.       8 red#junior
  10.       9 brown-2#senior
  11.      10 yellow#senior
  12.      11 red#junior
  13.      12 blue#senior
  14.      13 green#senior
  15.      14 purple#junior
  16.      15 white#junior
复制代码

awk脚本

  1. $vi belts.awk
  2.       1 #!/bin/awk -f
  3.       2 BEGIN{FS="#"
  4.       3         belt["yellow"]
  5.       4         belt["orange"]
  6.       5         belt["red"]
  7.       6         student["junior"]
  8.       7         student["senior"]
  9.       8 }
  10.       9 {for (colour in belt)
  11.      10    {if ($1==colour)
  12.      11    belt[colour]++}}
  13.      12 {for (senior_or_junior in student)
  14.      13    {if ($2==senior_or_junior)
  15.      14     student[senior_or_junior]++}}
  16.      15 END{ for (colour in belt) print "The club has", belt[colour], colour, "belts"
  17.      16 for (senior_or_junior in student) print "The club has", student[senior_or_junior], senior_or_junior, "students"}
复制代码


最后用命令输出

  1. $ belts.awk grade_student

  2. The club has 2 orange belts
  3. The club has 2 red belts
  4. The club has 3 yellow belts
  5. The club has 7 senior students
  6. The club has 8 junior students
复制代码


请高人指点一下这里for语句里or左右两边下划线的用法。
作者: ly5066113    时间: 2008-10-09 14:23
senior_or_junior 只是一个自定义的变量,可以换成任何你想用的。
作者: Siete    时间: 2008-10-09 14:29
再仔细看看是那么回事,是自己想复杂了。 谢谢了。
作者: xwmhmily    时间: 2008-10-09 20:44
无特别意思,变量名中的一部分
作者: sea_soft    时间: 2008-10-28 16:21
谢谢楼主,正好练习awk,懒得输入,这下可以直接COPY一份了




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2