awk command in linux

awk command in linux

We are going to see how to use awk command in Linux in this post.

It’s a scripting language and it’s used to generate Reports and Data Manipulation.

Syntax:

#awk <option> 'criteria {action}' input_file > output_file

Awk command to print file content:

[root@localhost ~]# awk '{print}' testfile.txt
Abu 1234
Thahir 5678
Tharun 9101
Rishi 2345

Above example is only to print all the content of a file.

Awk command to print the lines which match with the given pattern:

[root@localhost ~]# awk '/Rishi/{print}' testfile.txt
Rishi 2345

awk command to split a line to fields:

$1 will be considered the first word as the first field in a line. accordingly $2,$3, etc…

[root@localhost ~]# awk '{print $2}' testfile.txt
1234
5678
9101
2345
[root@localhost ~]#

Built-in variables in awk:

NF:     We can print the last field of the lines by using NF in awk command

Example: 

[root@localhost ~]# awk '{print $NF}' testfile.txt
25000
30000
20000
15000

NR:     Using NR built-in option, we can print the specific fields along with line numbers and can print all content of a file along with the line numbers. Also, we can print the range of lines using NR in awk command.

Examples:

1. Displaying specific row with a specific field in a file

[root@localhost ~]# awk 'NR==2 {print $1,$3}' testfile.txt
Thahir 30000

2.Displaying content of a range of lines(from 2 to 4th line)

[root@localhost ~]# awk 'NR==2, NR==4 {print $1,$3}' testfile.txt
Thahir 30000
Tharun 20000
Rishi 15000

 

Thanks for reading our blog. Please drop your comments.

Leave a Reply

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