awk编程参考

模式Patterns

AWK支持以下模式:

其中:

字符串匹配模式

动作Actions

AWK支持以下动作:

AWK内置变量

AWK支持的运算符

内置数学函数

内置字符串函数

流程控制语句

输出语句

例子

$3 > 15 { emp = emp + 1 }
END { print emp, "employees worked more than 15 hours" }

{ pay = pay + $2 * $3 }
END { print NR, "employees"
      print "total pay is", pay
      print "average pay is", pay/NR
}

$2 > maxrate { maxrate = $2; maxemp = $1 }
END { print "highest hourly rate:", maxrate, "for", maxemp }

{ nc = nc + length($0) + 1
  nw = nw + NF
}
END { print NR, "lines,", nw, "words," nc, "characters" }

{ for (i = 1; i <= $3; i = i + 1)
      printf("\t%.2f\n", $1 * (1 + $2) ^ i)
}

{ line[NR] = $0 }
END { for (i = NR; i > 0; i = i - 1)
          print line[i]
}

BEGIN { FS = "\t"
        printf("%10s %6s %5s    %s\n\n", "COUNTRY", "AREA", "POP", "CONTINENT")
}
{ printf("%10s %6d %5d    %s\n", $1, $2, $3, $4)
  area = area + $2
  pop = pop + $3
}
END { printf("\n%10s %6d %5d\n", "TOTAL", area, pop) }

BEGIN {
    sign = "[+|-]?"
    decimal = "[0-9]+[.]?[0-9]*"
    fraction = "[.][0-9]+"
    exponent = "([eE]" sign "[0-9]+)?"
    number = "^" sign "(" decimal "|" fraction ")" exponent "$"
}
$0 ~ number

/Asia/ { pop["Asia"] += $3 }
/Europe/ { pop["Europe"] += $3 }
END { print "Asian population is", pop["Asia"], "million."
      print "Europe population is", pop["Europe"], "million."
}

BEGIN { FS = "\t" }
{ pop[$4] += $3 }
END { for (name in pop) print name, pop[name] }

BEGIN {
    srand()
    for (i = 0; i < 150; i++) x[int(101*rand()/10)] += 1
}
END {
    for (i = 0; i < 10; i++)
        printf(" %2d - %2d: %3d %s\n", 10*i, 10*i+9, x[i], rep(x[i], "*"))
    printf("     100: %3d %s\n", x[10], rep(x[10], "*"))
}
function rep(n, s, t) {
    while (n-- > 0) t = t s
    return t
}
Table of Contents