awk
  awk通常由以下3部分构成:

  BEGIN{ 这里面放的是执行前的语句 }

  END {这里面放的是处理完所有的行后要执行的语句 }

  {这里面放的是处理每一行时要执行的语句}

假如有以下表:

$ cat score.txt
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

统计所有人有总钱数,及平均情况的awk脚本:

#!/bin/awk -f
#运行前
BEGIN {
    math = 0
    english = 0
    computer = 0
 
    printf "NAME    NO.   MATH  ENGLISH  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
}

输出结果:

NAME    NO.   MATH  ENGLISH  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

原文来自:

本文地址://gulass.cn/shell-awk.html编辑:向云艳,审核员:逄增宝

Linux大全:

Linux系统大全:

红帽认证RHCE考试心得: