AWK command examples

Today, we will see some AWK command examples.

What is AWK?

AWK is a powerful command-line tool that 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 a lot helpful when you are writing shell scripts. Let’s check out Awk without wasting more time 🙂

AWK command examples

Create a data file

Let’s create a file called data.txt with the following contents so that we can execute our awk commands on these it.

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

1. Printing Data

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

$ awk '{print}' data.txt

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

2. Printing Matching Lines

If you want to print all the lines matching a specific word. In our example, we are using the word America to search.

$ awk '/America/ {print}' data.txt
Bob America Married 50
John America Unmarried 18

You can also use the command below for the same thing.

$ awk /'America'/ data.txt
Bob America Married 50
John America Unmarried 18

3. Print data from a column.

You should be able to print the data from a specific column. In our example, we are printing age which resides in column 4 in our data.txt file.

$ awk '{print $4}' data.txt
50
25
33
28
18
16

4. Printing two columns

It is possible to also print two columns at the same time. In our example, we are printing Names and ages from the file.

$ awk '{print $1, $4}' data.txt
Bob 50
Jay 25
Abdul 33
Mona 28
John 18
Neha 16

You could also use the $NF if you want to print the last column.

$ awk '{ print $NF }' data.txt
50
25
33
28
18
16

5. Changing the order of columns.

Without changing the actual file, you can choose how your data is printed on the screen. In our file, we have entered the name first, however, awk can print age first for you without changing the actual file.

$ awk '{print $4, $1}' data.txt
50 Bob
25 Jay
33 Abdul
28 Mona
18 John
16 Neha

6. 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 America is present in column 2 it will print the column 1

$ 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.

Another example, if you want to print all the people whose age is below 30 you can use this command.

$ awk '$4 <  30 { print $0 }' data.txt
Jay India Unmarried 25
Mona London Married 28
John America Unmarried 18
Neha India Unmarried 16

AWK can do much more, I have just specified some basic AWK command examples above. I will come up with an advanced AWK article soon.

Spread the love

Leave a Comment