在awk 中,匹配模式处于非常重要的地位,它决定着匹配模式后面的操作会影响到哪些文本行。 awk 中  
 
 的匹配模式主要包括关系表达式、正则表达式、混合模式, BEGIN 模式以及 END 模式等。  
 
 ( 1 )关系表达式  
 
 awk 提供了许多关系运算符,例如大于>、小于<或者等于 == 等。 awk 允许用户使用关系表达式作为匹  
 
 配模式,当某个文本行满足关系表达式时,将会执行相应的操作。 
 
 
 [root@localhost test11] # cat file  
  liming  80  
  wangmei  70  
  zhangsan  90  
  lisi  81  
  [root@localhost test11] # awk '$2 > 80 {print}' file  
  zhangsan  90  
  lisi  81  
   ( 2 )正则表达式  
  awk 支持以正则表达式作为匹配模式,与 sed 一样,用户需要将正则表达式放在两条斜线之间,其基本语  
  法如下: /regular_expression/  
   [root@localhost test11] # awk '/^l/{print}' file  
  liming  80  
  lisi  81  
  [root@localhost test11] # awk '/^l|z/{print}' file  
  liming  80  
  zhangsan  90  
  lisi  81  
   ( 3 )混合模式  
  awk 不仅支持单个的关系表达式或者正则表达式作为模式,还支持使用逻辑运算符 && 、 || 或者 ! 将多个  
  表达式组合起来作为一个模式。其中, && 表示逻辑与, || 表示逻辑或, ! 表示逻辑非。  
   [root@localhost test11] # awk '/^l/ && $2>80 {print}' file  
  lisi  81  
   ( 4 )区间模式  
  awk 还支持一种区间模式,也就是说通过模式可以匹配一段连续的文本行。区间模式的语法如下:  
  pattern1, pattern2  
  其中, pattern1 和 pattern2 都是前面所讲的匹配模式,可以是关系表达式,也可以是正则表达式等。当  
  然,也可以是这些模式的混合形式。  
   [root@localhost test11] # awk '/^liming/,$2==90 {print}' file  
  liming  80  
  wangmei  70  
  zhangsan  90  
   ( 5 ) BEGIN 模式  
  [root@localhost test11] # cat 1.sh  
  #!/bin/awk -f  
  BEGIN {print  "hello,world" }  
  [root@localhost test11] # ./1.sh  
  hello,world  
  [root@localhost ~] # awk -F: 'BEGIN {printf "%-15s %-3s  
  %-15s\n","user","uid","shell"} $3==0,$7~"nologin" {printf "%-15s %-3s  
  %-15s\n",$1,$3,$7}' /etc/passwd  
   ( 6 ) END 模式  
  [root@localhost test11] # cat 2.sh  
  #! /bin/awk -f  
  BEGIN {  
  print  "scores report"  
  print  "================================="  
  }  
  { print }  
  END {  
  print  "================================"  
  print  "printing is over"  
  }  
  [root@localhost test11] # ./2.sh file  
  scores report  
  =================================  
  liming  80  
  wangmei  70  
  zhangsan  90  
  lisi  81 
  ================================  
  printing is over  
  [root@localhost ~] # awk -F: 'BEGIN {printf "%-15s %-3s  
  %-15s\n","user","uid","shell"} $3==0,$7~"nologin" {printf "%-15s %-3s  
  %-15s\n",$1,$3,$7} END {print "-----End file-----"}' /etc/passwd