10 AWK Print Statement Examples ( AWK Scripting )

awk-command-examples
mm
Written By:- Santosh Prasad

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

# 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:)

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

Other Post by Santosh Prasad

Visit All Post

Related Article

You may also Like

Leave a Comment

Shares