• General Syntax of awk: awk -f {awk program file} filename
  • The format of awk program looks like:

[pattern] {
Action 1

Action 2
..
Action N
}

  • Summery of common awk metacharacters:

Metacharacter

Meaning

. (Dot)

Match any single character

*

Match zero or more character

^

Match beginning of line

$

Match end of line

\

Escape character following

[ ]

List

{ }

Match range of instance

+

Match one more preceding

?

Match zero or one preceding

|

Separate choices to match

  • Built in awk variables

awk Variable

Meaning

FILENAME

Name of current input file

RS

Input record separator character (Default is new line)

OFS

Output field separator string (Blank is default)

ORS

Output record separator string (Default is new line)

NF

Number of fields in input record

NR

Number of input record

OFMT

Output format of number

FS

Field separator character (Blank & tab is default)

  • Ex: create a plain file "inven" with the contents of last 4 lines.

Sr. No

Product

Qty

Unit Price

1

Pen

5

20.00

2

Rubber

10

2.00

3

Pencil

3

3.50

4

Cock

2

45.50

$awk '{ print $1 $2 "--> Rs." $3 * $4 }' invent        /* $1, $2, $3, and $4 stand for field 1, 2, 3, 4 respectively in a record */

 

$vi prn_pen.awk
/Pen/ { print $3 }   ## /Pen/ is the searching pattern ##
$awk -f prn_pen.awk invent

 

$vi comp_inv.awk
$3>5 { print $0 }   ## $3>5, select the record that the value of column3 larger than 5, $0 stands for all fields in a record ##
$ awk -f comp_inv.awk invent          

 

$vi def_var.awk
{
         print "Printing Rec. #" NR "(" $0 "), and # of field for this record is " NF

}
$awk -f def_var.awk inven

  • User defined variables and printf in awk
    Ex:
    $vi bill.awk
    BEGIN {                 ## BEGIN pattern, perform BEGIN actions before the first line (Record) has been read from database file ##
        printf "---------------------------\n"
        printf "Account\n"
        printf "---------------------------\n"
    }
    {
        total = $3 * $4  ## user defined variable ##
        recno = $1        ## user defined variable ##
        item = $2          ## user defined variable ##
        gtotal += total
        printf "%2d %-10s Rs.%7.2f\n", recno, item, total    ## Just like printf() in C lnaguage ##
    }
    END {                     /* END pattern, perform END actions after reading all lines (RECORD) from the database file */
        printf "---------------------------\n"
        printf "\tTotal Rs. %7.2f\n" ,gtotal
        printf "---------------------------\n"
    }
    $ awk -f bill.awk inven
  • if condition in awk
    Syntax:
    if ( condition ){
        statement 1
        statement 2
        ...
        statement N
    }else{
        statement 1
        statement 2
        ...
        statement N
    }
  • Ex:
    $vi math.awk
    BEGIN {
       myprompt = "(To Stop press CTRL+D) > "
       printf "Welcome to Addtion calculation awk program\n"
       printf "%s" ,myprompt
    }
    {
        no1 = $1
        op = $2
        no2 = $3
        ans = 0
        if ( op == "+" ){
            ans = $1 + $3
            printf "%d %c %d = %d\n" ,no1,op,no2,ans
            printf "%s" ,myprompt
        }else{
            printf "Opps!Error I only know how to add.\nSyntax: number1 + number2\n"
            printf "%s" ,myprompt
        }
    }
    END {
        printf "\nGoodbye %s\n" , ENVIRON["USER"]
    }

    $awk -f math.awk
  • ENVIRON is the one of the predefined system variable that is array. ENVIRON can be used to access environment variables.
  • loop in awk
    Syntax:
    for (expr1; condition; expr2){
               statement 1
               statement 2
               statement N
    }
    while (condition){
               statement1
               statement2
               statementN
    }
  • Ex:
    $vi for.awk
    BEGIN{
               printf "Press ENTER to continue with for loop example\n"
    }
    {
               sum = 0
               i = 1
               for (i=1; i<=10; i++){
                         sum += i
               }
               printf "Sum for 1 to 10 numbers = %d \nGoodbye!\n", sum
               exit 1
    }

    $awk -f for.awk
    Ex:
    $vi while.awk
    {
               no = $1
               remn = 0
               while ( no > 1 ){
                         remn = no % 10
                         no /= 10
                         printf "%d" ,remn
               }
               printf "\nNext number please (CTRL+D to stop):"
    }

    #awk -f while.awk
  • Ex: copy files
    $vi filelist.conf
    ~/1.txt /tmp
    ~/2.txt /tmp
    $vi cp.awk
    BEGIN{
    }
    {
               sfile = $1
               dfile = $2
               cpcmd = "cp " $1 " " $2
               printf "Copying %s to %s\n",sfile,dfile
               system(cpcmd)    ## system() function execute given system command ##
    }
    END{
    }

    $awk -f cp.awk filelist.conf
  • Ex: remove files
    $vi rm.awk
    {
               dcmd = "rm " $1
               if( system(dcmd) != 0 )
                         printf "rm command not successful\n"
               else
                         printf "rm command is successful and %s file is removed \n", $1
    }

    $awk -f rm.awk
  • getline
    Syntax:
    getline < "file-name"                 /* read input from file */
    "command" | getline                 /* read input from pipe */
  • Ex:
    $vi getline.awk
    BEGIN{
               printf "Your name please:"
               getline na < "-"
               printf "%s your age please:",na
               getline age < "-"
               age++
               printf "Hello %s, next year you will be %d\n", na, age
    }

    $awk -f getline.awk
    $vi date.awk
    BEGIN{
               "date" | getline
               print $0
               "date" | getline today
               print $today
    }

    $awk -f date.awk
arrow
arrow
    全站熱搜

    nix 發表在 痞客邦 留言(0) 人氣()