Linux Administrator

Best AWK Command Examples in Linux/Unix

In this article I will show you best AWK command examples. You will learn AWK print statement with examples as print statement is one of the most used AWK command. For AWK print statement, I have taken a test file as below:

Best AWK Command Example in Linux/Unix

Here are the some AWK command examples.

# cat test.txt

Santosh,Sagar 1 2 3 4
New,Jimmy 5 6 7 8
Gorge,Mirza 9 10 11 12
Trinity,Manoj 13 14 15 16
Same,Sumit 17 18 19 20
Avinash,Deepak 21 22 23 24
Wooda,Supan 25 26 27 28
Dellam,July 29 30 31 32
Lyth,july 33 34 35 36
Jimmy,Suresh 37 38 39 40

Examples

1. Search for ‘Same’ word in the file and print those lines. This is same like grep.

# awk '/Same/' test.txt

You will get some output like below:

Same,Sumit 17 18 19 20

2. Search for a word and print the lines which contain either July or july in the test.txt file.

# awk ‘/[Jj]uila/’ test.txt

You will get some output like below:

Dellam,July 29 30 31 32
Lyth,july 33 34 35 36

In the above example we used regular expression to match both July and july.

3. Print a particular column from test.txt file.

# awk ‘{print $2}’ test.txt

Sample output:

1
5
9
13
17
21
25
29
33
37

4. Print multiple columns from test.txt file.

# awk ‘{print $2,$4}’ test.txt

Sample output:

1 2
5 6
9 10
13 14
17 18 
21 22
25 26
29 30
33 34
37 37

5. Print multiple columns with a tab between columns as separator from given file.

# awk ‘{print $2,”t”,$4}’ test.txt

Sample output:

1 2
5 6
9 10
13 14
17 18 
21 22
25 26
29 30
33 34
37 37

6. Search for ‘Avinash‘ word and print the corresponding third column.

# awk ‘/Avinash/{print $3}’ test.txt 

Sample output:

21

7. Print line number more than 5.

# awk ‘NR>5’ test.txt

Sample output:

Avinash,Deepak 21 22 23 24
Wooda,Supan 25 26 27 28
Dellam,July 29 30 31 32
Lyth,july 33 34 35 36
Jimmy,Suresh 37 38 39 40

NR is a inbuilt variable which keeps the line numbers of a file.

8. Print lines from 3 to 6.

# awk ‘NR>3 && NR 7> test.txt

Sample output:

Trinity,Manoj 13 14 15 16
Same,Sumit 17 18 19 20
Avinash,Deepak 21 22 23 24

9. Print only lines which has 18 in it’s third column.

# awk’$3 ~/29/’ test.txt

Sample output:

Same,Sumit 17 18 19 20

10. Print the column 5 if the column 3 contain 22 in it.

# awk ‘$3 ~/22/{print $5}’ test.txt

Sample output:

24

I hope this article will be helpful for you.

Thanks:)

Thank you! for visiting LookLinux.

If you find this tutorial helpful please share with your friends to keep it alive. For more helpful topic browse my website www.looklinux.com. To become an author at LookLinux Submit Article. Stay connected to Facebook.

About the author

mm

Santosh Prasad

Hi! I'm Santosh and I'm here to post some cool article for you. If you have any query and suggestion please comment in comment section.

Leave a Comment