An Awk Primer/Nawk

< An Awk Primer

The original version of Awk was developed in 1977. It was optimized for throwing together "one-liners" or short, quick-and-dirty programs. However, some users liked Awk so much that they used it for much more complicated tasks. To quote the language's authors: "Our first reaction to a program that didn't fit on one page was shock and amazement." Some users regarded Awk as their primary programming tool, and many had in fact learned programming using Awk.

After the authors got over their initial consternation, they decided to accept the fact, and enhance Awk to make it a better general-purpose programming tool. The new version of Awk was released in 1985. The new version is often, if not always, known as Nawk ("New Awk") to distinguish it from the old one.


   {for (field=1; field<=NF; ++field) {print signum($field)}};

    function signum(n) {
       if (n<0)
       return -1
       else if (n==0) return 0
       else
           return 1}

Function declarations can be placed in a program wherever a match-action clause can. All parameters are local to the function. Local variables can be defined inside the function.

   getline                   Loads $0 from current input.
   getline myvar             Loads "myvar" from current input.
   getline myfile            Loads $0 from "myfile".
   getline myvar myfile      Loads "myvar" from "myfile".
   command | getline         Loads $0 from output of "command".
   command | getline myvar   Loads "myvar" from output of "command".

   close("myfile")
   system("rm myfile")

   status = (condition == "green")? "go" : "stop"

This translates to:

   if (condition=="green") {status = "go"} else {status = "stop"}

This construct should also be familiar to C programmers.

   sin(x)         Sine, with x in radians.
   cos(x)         Cosine, with x in radians.
   atan2(y,z)     Arctangent of y/x, in range -PI to PI.
   rand()         Random number, with 0 <= number < 1.
   srand()        Seed for random-number generator.


   BEGIN {count = 1;
      for (row = 1; row <= 5; ++row) {
        for (col = 1; col <= 3; ++col) {
          printf("%4d",count);
          array[row,col] = count++; }
        printf("\n"); }
      printf("\n");

      for (col = 1; col <= 3; ++col) {
         for (row = 1; row <= 5; ++row) {
            printf("%4d",array[row,col]); }
         printf("\n"); }
      exit; }

This yields:

   1   2   3    4   5   6    7   8   9    10  11  12    13  14  15

   1   4   7  10  13    2   5   8  11  14    3   6   9  12  15

Nawk also includes a new "delete" function, which deletes array elements:

   delete(array[count])


This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.