Awk Workshop
Introduction
AWk is a text processing language usually used for the following:
- tallying information from text files and creating reports from the results
- translating files from one format to another
- performing mathematical operations on files with numerical data
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:
- Host Name : willow.olemiss.edu
- User Name : student
- Password : Will be provided during the workshop
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
- Print all records
- awk '{print $0}' student.txt
- Print names of all students
- awk '{print $1}' student.txt
- now try.... awk 'BEGIN {FS="\t"} {print $1}' student.txt
- Print records with the name Daniel Mathew
- awk 'BEGIN {FS="\t"} /Daniel Mathew/ {print $0}' student.txt
- Print recods with Unix as workshop
- awk 'BEGIN {FS="\t"} /Unix/ {print $0}' student.txt
- Print total number of records
- awk 'END {print NR}' student.txt
- Print number of feilds
- awk 'BEGIN {FS="\t";num=0;} {num= NF} END {print num}' student.txt
- Print student records with a score 8 or above
- awk 'BEGIN {FS="\t"} {if($3>=8) print $0}' student.txt
- 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