You are on page 1of 10

AWK

A Tutorial

June 5, 2012

We deliver Global Engineering Solutions. Efficiently.

2011 Infotech Enterprises. All Rights Reserved

Why AWK ?

Simple, Small and Fast


Stable interpreter Easy to learn Easy availability of Software (Default in unix/linux) http://www.math.utah.edu/docs/info/gawk_13.html

2011 Infotech Enterprises

Why NOT AWK ?

Once you learn AWK, it will be difficult to migrate to Perl


Limited features Line by line execution Round-about way to solve complex problems

2011 Infotech Enterprises

AWK How to run

Unixprompt % awk f <awk_scr> <file_on_which_awk_scr_to_beexecuted>

Ex:Unixprompt % awk f awk1 file.txt

2011 Infotech Enterprises

Structure of an AWK program

BEGIN { Variable declaration } # Optional


{ Main AWK program } END { Post processing statements} # Optional

2011 Infotech Enterprises

AWK The beginning

Awk treats each file as a matrix.


Each field in a line is separated by Space $0 Entire current line $1 First word in current line $5 Fifth word in the current line

2011 Infotech Enterprises

AWK NF, NR, $NF, $NR, FS

FS = Field separator (Default is space, you can set it in BEGIN block)


NF = No of fields in current line (Changes based on FS) $NF = Last field in current line NR = Current lines sequential number. $NR = meaningless Variable declaration not required (Same as Perl)

2011 Infotech Enterprises

Some elementary programs

Write a program to print the sum of fields in a each line of a data file
Write a program to print the fields in each line in the reverse manner.

2011 Infotech Enterprises

AWK Functions

getline;

$0 will be updated with next line

Index (p, q) Returns the position of q in p (If no find, returns 0) length (str) returns the length of str split (str, arr [, fs]) splits str based on field separator fs and stores in arr tolower (str) converts str to lower case toupper (str) converts str to upper case Sub(reg_exp,

2011 Infotech Enterprises

Thank You

www.infotech-enterprises.com

We deliver Global Engineering Solutions. Efficiently.

2011 Infotech Enterprises. All Rights Reserved

You might also like