A little AWK tutorial

 
 
Posts: 3899
Joined: 2006-12-21
Points: 0
User is offline
A little AWK tutorial

The work "AWK" is derived from the its three developers: A. Aho, B. W. Kernighan and P. Weinberger.
Typical Strucutre of AWK programs is same as C where we uses Blocks. Each block in AWK starts with BEGIN and ends with END
Here is a small prgoram of AWK code -
#!/bin/awk -f BEGIN { print "File\tType is Awk" } { print $5, "\t", $6} END { print " - FINISH -" }
Run the Program by awk -f filename
Now here are Few AWK Programs, try to understand them. They are fairly self explainatory -
1. The following asks for a number, and then squares it:

#!/bin/awk -fBEGIN {    print "type a number";}{    print "The square of ", $1, " is ", $1*$1;    print "type another number";}END {    print "Done"}

At this point, you can use AWK as a language for simple calculations; If you wanted to calculate something, and not read any lines for input, you could use the BEGIN keyword discussed earlier, combined with a exit command:
#!/bin/awk -fBEGIN {# Print the squares from 1 to 10 the first way	i=1;	while (i <= 10) {		printf "The square of ", i, " is ", i*i;		i = i+1;	}# do it again, using more concise code	for (i=1; i <= 10; i++) {		printf "The square of ", i, " is ", i*i;	}# now endexit;}
You can Find some real good AWK content here Enjoy