Search This Blog

Saturday, October 9, 2010

AWK - A text processing language

Awk - A Text Processing language

              Awk is a text processing language, it is very useful for the following Tasks.

  • Tallying information from text files and creating reports from the results.
  • Adding additional functions to the editiors like "vi".
  • Translating files from one format to another format.
  • Creating small databases.
  • Performing mathematical operations on files of numeric data.
There are some predifined variables available  for AWK.

     NR -  Number of Records
     NF -  Number of Fields
     FS -  Field Separator character
     RS -  Record Separator character
     OFS - Output Field Separater
     ORS - Output Record Separater


Simplest general form of an AWK program

      awk  'BEGIN               {<initializations >} 
          <search pattern 1> {<program actions>}
          <search pattern 2> {<program actions>}
          <search pattern 3> {<program actions>}
          ....
                END                   {<Final actions>}

   Examples:
         
        coins.txt file contains the following data

    metal   weight  dateminted country                 description

      gold    1            1986         USA                      American Eagle
      gold    1            1908         Austria-Hungary   Franz Josef 100 korona
      silver   10          1981        USA                      Ingot
      gold     1            1984        Switzerland          Ingot
      gold     1            1979        RSA                     Krugerrand
      gold     0.5         1981        RSA                     Krugerrand
      gold     0.1         1986       PRC                     Panda
      silver    1            1986       USA                     Liberty doller

      If we want to search particular word (gold )in a file and print particular fields (5,6,7,8) :


   awk '/gold/ { print $5,$6,$7,$8 } ' coins.txt

     If we want to use filter for the perticular filed ( 3rd field) then :

   awk ' { if ($3 <1980) print $3, "     " $5,$6,$7,$8 }' coins.txt

   
     If we want to find the number of records in the perticular file then:

   awk ' END { print NR, "coins" } ' coins.txt

      If we want to take the total value in a particular field then :


   awk ' /gold/ { ounces += $2} END  { print "value = $" 425*ounces}' coins.txt   

      If we want to create Fibonacci Sequence then :
   awk ' BEGIN { a=1;b=1; while (++X<=10 ) { print a; t=a;a=a+b;b=t}  exit}'

      Remember that AWK is a relatively slow and clumsy and should not be regarded as the default tool for all specific jobs. We can use "cat" to append the files and "head" and "tail" to cut off a given number of lines from a particular file from top and bottom of a file, and "grep" and "fgrep" to find particular lines from a file, and "sed" is used to replace the particular word in a file.
  
     

No comments:

Post a Comment