awk 最大值,最小值 字符串转数字

    技术2022-05-20  41

    马上就要用awk来分析一些日志,所以今天继续恶补。书上的例子看了就懂,有些飘飘然。然而真正动手却发现不是那么回事。看来好记性不如烂笔头,有些东西记下来比较好。

    举个最简单的例子吧,用awk求一列的最大值和最小值。按照书中的要求来写出内容。其中最让人恶心的大概就是这个字符串转数字了。

    BEGIN {     FS= "[:]";         print "                       ***CAMPAIGN 1998 CONTRIBUTIONS***                   /n";     print "---------------------------------------------------------------------------/n";     printf "%-20s/t"s/t%8s/t%8s/t%8s/t%8s/t/n", "NAME", "PHONE", "Jan  |", "  Feb|", "Mar  |", "TotalDonated";     print "---------------------------------------------------------------------------/n"; } {     if ( NR == 1 ) {         min = $3+ 0;         max = $5+ 0;     } else {         if ( ( $3+ 0 ) < min ) { min = $3+ 0 }         if ( ( $5+ 0 ) > max ) { max = $5+ 0 }     }     $6 = $3+ $4+ $5;     total += $6;     printf "%-25s/t"s/t%8s/t%6.2f/t%6.2f/t%6.2f/t/n", $1, $2, $3, $4, $5, $6;     } END {     avg = total /NR;         print "--------------------------------------------/n";     print "                 SUMMARY                    /n";     printf "The campaign received a total of $%6.2 for this quarter./n",total;     printf "The everage donation for the "NR " contribuors was $%6.2f/n",avg;     printf "The highest contribution was $%6.2f/n",max;     printf "The lowest contribution was $%6.2f/n",min; }

    如果min = $3+0; max = $5+0;这里不写上这个+0的话,得出的最大值最小值是按字符串方式比较的。(这个我现在也不敢肯定了,不过至少在我的服务器环境下面是这样的,我怀疑和我拷贝过去的原数据文件格式有关,可能在最后一列后面多出空格之类的东西)

    现结果如下:

    awk_min_max


    最新回复(0)