The AWK Programming Language | AWK 编程语言

虽然全书没有看完(作者也说看第一章就够了),但还是要底气很足地说这本书真的很好。作者信手拈来各种好的例子。

An Awk Tutorial

Get Started

Hello World Example: awk '$3 > 0 {print $1, $2 * $3}' data.txt

The Structure Of AWK Program

Simple Output

What AWK Can?

Printing Fields, Selecting Input, And Transforming Data

Fancier Output

printf ("format", value1, value2, ...)
Sorting

awk '{ printf("%6.2f %s\n", $2 * $3, $0) }' emp.data | sort

Selection

Computing with AWK

Counting
{ counter = counter + 1 }
END { print ("there are %d lines.\n", counter) }

Computing Sums and Average

Handing Text

String Concatenation
    { names = names $1 " " }
END { print names }
Printing the Last Input Line
    { last = $0 }
END { print last }
Built-in Functions

{ print $1, length($1) }

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

Control-flow statements

Arrays

Print Input In Reverse Order By Line
{ line[NR] = $0 }
END { i = NR
      while (i > 0) {
      print line[i]
      i = i - 1
      }
}

A Handful Of Useful “One-Liners”

WHAT’S NEXT

THE AWK LANGUAGE

Data

USSR    8649  275   Asia
Canada  3852  25    North America
China   3705  1032  Asia
USA 3615  237   North America
Brazil  3286  134   South America
India   1267  746   Asia
Mexico  762   78    North America
France  211   55    Europe
Japan   144   120   Asia
Germany 96    61    Europe
England 94    56    Europe

program format: one line or multi lines breaks with “"

DATA PROCESSING

histgram:

    { data[int($1/10)]++ }
END { for (i=0; i<10; i++)
          printf("%s", rep(data[i], "*"))
}

function rep(n, s, t)
{
    while (n-- > 0)
       {
    t = t s
       }
    return t
}

convert mmddyy to yymmdd: { $1 = substr($1,5,2) substr($1,1,2) substr($1,3,2) print $1 }

reports and databases

processing words

little languages

experiments with algorithms

epilog


Refs

  1. The AWK Programming Language (豆瓣)

「Load Disqus | 加载评论」