Basic AWK command examples.

Along with SED command Linux – AWK is powerful command line tool which would help you to perform a lot of actions on your data. It can help you to sort, print and process your data in the way you like. You can use AWK to read and edit the file.

AWK is mostly used in the Shell Scripts. Lets check out Awk without wasting more time 🙂

Let’s create a file called data.txt with the following contents – so we can learn AWK command better with examples.

Bob America Married 50
Jay India Unmarried 25
Abdul UAE married 33
Mona London Married 28
John America Unmarried 18
Neha India Unmarried 16

Run the command below which will print the contents in the file as it is.

[root@server ~]# awk '{print}' data.txt

Bob America Married 50
Jay India Unmarried 25
Abdul UAE married 33
Mona London Married 28

Print all the lines Matching with America.

[root@server ~]# awk '/America/ {print}' data.txt
Bob America Married 50
John America Unmarried 18

Only Print age from the file. As you can see that Age is written in the 4 column so we will use the command below.

[root@server ~]# awk '{print $4}' data.txt
50
25
33
28
18
16
[root@server ~]#

So now if you want to print Name and Age.

[root@server ~]# awk '{print $1, $4}' data.txt
Bob 50
Jay 25
Abdul 33
Mona 28
John 18
Neha 16

You can print age first by changing the order.


[root@server ~]# awk '{print $4, $1}' data.txt
50 Bob
25 Jay
33 Abdul
28 Mona
18 John
16 Neha
[root@server ~]#

Conditional Printing

I would like to print the names of the people who live in America. So here you will use If Condition in awk. In the example below it will check if the America is present in the column 2 it will print the column 1

[root@server ~]# awk '{ if ($2 == "America") print $1;}' data.txt
Bob
John

In the above example, if you just put awk ‘{ if ($2 == “America”) print;}’ data.txt it will print the complete line.

AWK can do much more that what I have specified above. I will come up with Advanced AWK article soon.

Leave a Reply

Your email address will not be published. Required fields are marked *