AWK Command

  • Awk actually stands for the names of its authors: “Aho, Weinberger, & Kernighan”.
  • Used for pattern scanning / filtering
  • Command syntax :   awk  <search pattern> { action }

Example :

Consider the file test.log with the below data

server501:[DATA001] /home/oracle -> cat test.log

ANJELINA IS A GOOD GIRL

RAMU IS A GOOD BOY

DIYA  IS A GOOD GIRL

1: To check for the lines with word ANJELINA from the file test.log

server501:[DATA001] /home/oracle -> awk ‘/ANJELINA/’ test.log

ANJELINA IS A GOOD GIRL

>>> exactly similar to grep command . Output will show all the lines with the word ANJELINA. Here only search pattern is specified , not the action. By default, the action is to print the full line.

2. To print the 4th field from the line containing word ANJELINA

server501:[DATA001] /home/oracle -> awk ‘/ANJELINA/ { print $4 }’ test.log

GOOD

>>>> Here ANJELINA is the search pattern .  Printing  the 4th field (GOOD) is the action . test.log is the file name.

3. To print GOOD BOY from the line containing word RAMU

server501:[DATA001] /home/oracle -> awk ‘/RAMU/ { print $4 ” ” $5 }’ test.log

GOOD BOY

>>>>  In { print $4 ” ” $5 } action , double quotes add a space between GOOD and BOY. Otherwise the output will be GOODBOY.

4. To select the word RAMU from the file and add a text on our own to make a complete sentence

server501:[DATA001] /home/oracle -> awk ‘/RAMU/ {print $1 ” WILL COME FOR BREAKFAST ” }’ test.log

RAMU WILL COME FOR BREAKFAST

Consider another file test1.log with the below data

server501:[DATA001] /home/oracle -> cat test1.log

A BOOK COST 25 Rs

A PEN COST 10 Rs

A PENCIL COST 2 Rs

We can give conditions/functions within AWK command .

5. Print the objects whose cost is higher than 5 Rs

server501:[DATA001] /home/oracle -> awk ‘{if ($4 > 5 ) print $2}’ test1.log

BOOK

PEN

6. Print the cost of 5 pencils from the file using awk command

server501:[DATA001] /home/oracle -> awk ‘/PENCIL/ { print ” Price of five ” $2 “S = Rs” 5*$4 }’ test1.log

Price of five PENCILS = Rs10

Advantages of AWK command :

A. Awk can break a sentence into segments (fields) based on given criteria.

B. Allows to format the output in ways that might be easier to process further

C. Awk has arithmetic and string operators

D. Awk has variables, conditionals and loops