Awk Workshop


Introduction

AWk is a text processing language usually used for the following: Awk actually stands for the names of its authors: Aho, Weinberger and Kernighan.

Getting Started

Login to SSH secure shell client using the following information:

Sample Text

For todays workshop we will be using the file 'student.txt' that provides student scores for various workshops. Each line in the file contains the following information:

      Student-Name     Workshop-Name     Score


Syntax

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


Examples

  1. Print all records
    • awk '{print $0}' student.txt
  2. Print names of all students
    • awk '{print $1}' student.txt
    • now try.... awk 'BEGIN {FS="\t"} {print $1}' student.txt
  3. Print records with the name Daniel Mathew
    • awk 'BEGIN {FS="\t"} /Daniel Mathew/ {print $0}' student.txt
  4. Print recods with Unix as workshop
    • awk 'BEGIN {FS="\t"} /Unix/ {print $0}' student.txt
  5. Print total number of records
    • awk 'END {print NR}' student.txt
  6. Print number of feilds
    • awk 'BEGIN {FS="\t";num=0;} {num= NF} END {print num}' student.txt
  7. Print student records with a score 8 or above
    • awk 'BEGIN {FS="\t"} {if($3>=8) print $0}' student.txt
  8. Print average score of all records
    • awk 'BEGIN {FS="\t"; tot=0; avg=0;} {tot+=$3} END {avg=tot/NR; print "Avereage=" avg;}' student.txt