Getting Started:

 Useful awk programs are often short, just a line or two. Suppose you have a
file called emp.data that contains the name, pay rate in nrs per hour, and
number of hours worked for your employees, one employee record per line, like
this:

Ramesh       4.00          0
Samjhana   3.75           0
Asmita        4.00           10
Sandesh      5.00           20
Rajesh         4.25           18

Now you want to print the name and pay (rate times hours) for everyone who
worked more than zero hours. This is the kind of job that awk is meant for, so
it's easy.

prakash@prakash-VPCEB490X:~/Desktop$ awk ' $3 > 0 { print $ 1, $2 * $3 }' emp.data
 You should get this output:
Asmita 40
Sandesh 100
Rajesh 76.5

         Awk reads its input one line at a time and splits each line into fields, where,
by default, a field is a sequence of characters that doesn't contain any blanks or
tabs. The first field in the current input line is called $1, the second $2, and so
forth. The entire line is called $0. The number of fields can vary from line to
line.

prakash@prakash-VPCEB490X:~/Desktop$ awk '{print"total pay for", $1,"is", $2 * $3}'  emp.data
 You should get this output:
total pay for Ramesh is 0
total pay for Samjhana is 0
total pay for Asmita is 40
total pay for Sandesh is 100
total pay for Rajesh is 76.5

prakash@prakash-VPCEB490X:~/Desktop$ awk '{printf("total pay for %s is $%.2f\n", $1,$2 * $3)}' emp.data
 You should get this output:
total pay for Ramesh is $0.00
total pay for Samjhana is $0.00
total pay for Asmita is $40.00
total pay for Sandesh is $100.00
total pay for Rajesh is $76.50

 In the above output first, %s, says to print the first value, $1, as a string of characters; the second, %. 2f, says to print the second value, $2*$3, as a number with 2 digits after the decimal point. Everything else in the specification string, including the dollar sign, is printed verbatim; the \n at the end of the string stands for a newline, which causes subsequent output to begin on the next line.

Sorting the Output

Suppose you want to print all the data for each employee, along with his or
her pay, sorted in order of increasing pay. The easiest way is to use awk to pre-
fix the total pay to each employee record, and run that output through a sorting
program. On Unix, the command line
prakash@prakash-VPCEB490X:~/Desktop$ awk '{printf("%6.2f $%s\n", $2 * $3, $0)}' emp.data | sort
 You should get this output:
  0.00 $Ramesh    4.00   0
  0.00 $Samjhana   3.75   0
100.00 $Sandesh      5.00   20
 40.00 $Asmita       4.00   10
 76.50 $Rajesh     4.25   18


Comments

Popular posts from this blog

Challenging obstacles for immigrants

What is Linux Shell?

Permission and Ownership using awk