Learn AWK command — Part 2

Let’s see few examples how awk can work:

Using AWK as cut command

Take below table named worker.txt

100  David TM 4000

200  Kelvin SM 8000

300  Bobby RM 9000

Just you want 2 column what you will do ? cut command right ..

But you know we can do that using awk also and it is very simple than cut command

awk ‘{print $2}’ worker.txt


Simple, isn’t it?

Here $1 – represents first field

$2 –  represents second field

$0 – Entire line

Now you want to know the salary of Kelvin .. so you want that to be printed on screen

 awk ‘/Kelvin/ {print $4} ‘ worker.txt

If you want salaries of both Bobby and David

awk ‘/Bobby/ {print $4} /David/ {print $4}’ worker.txt 

What if you want two column values for same user

awk ‘/bobby/ {print $4 “ “  $3} ‘ worker.txt

“ “ will separate the two values by space , you can any delimiter to separate the both column values .

In our example

100  David TM 4000

200  Kelvin SM 8000

300  Bobby RM 9000

Fields are separated by space, what if another delimiter is used to separate the fields

By default awk uses space to identify the fields . So whenever you have fields separated by other than space we need to use -F option followed by the delimiter in double quotes

Take below example

Suppose you want user id of user Michel from /etc/passwd file.

As we know the /passwd file arrangement is like below:





As we discussed earlier , awk treats 1 line as 1 record so here we have 4 records and each record contains 7 fields separated by “:”.

so here the command is

awk -F “:” ‘{print $1}’ passwd


Similarly if you want the user id and home directory path of user kelvin

awk -F “:” ‘ /kelvin/ {print $3 “ “ $6} ‘ passwd


Till now we saw simple usage of awk command .. to go forward we need to learn about in built variables of awk



Express your Opinion here

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s