How to print a particular line using awk in bash shell linux ?

In this article we will see how to print a particular line from a file in Linux using awk command.

Many of the times, we need to grep a particular line of the file and by using below trick we can get the particular line from a file in Linux.

We can accomplish this task using sed also, however there is one more easy way to do this by using awk command.

Lets have a look at this command.

1. How to print a particular line from a file.
To accomplish this, we will see how to use awk NR bultin.

### Below is a sample file named file4
[root@nglinux ~]# cat file4
1. hello "good" ***
2. how  "good" ***
3. are  "good" ***
4. you "good" ***

### Lets print its second line
[root@nglinux ~]# awk 'NR==2' file4 
2. how  "good" ***

### Lets print 3rd line
[root@nglinux ~]# awk 'NR==3' file4 
3. are  "good" ***

2. How to print a particular range of lines from a file ?
In the above example we made NR with one single row, and here we will assign a list of rows.

### Lets print lines 3 and 4 from the file file4.
[root@nglinux ~]# awk 'NR >= 3 && NR <= 4' file4 
3. are  "good" ***
4. you "good" ***
[root@nglinux ~]# 

Seems interesting !!!

Here we have used awk NR i.e. number of rows builtin to reduce the number of rows and print the specified rows from the file.

Do post your comment/suggestions below.

Leave a Reply

avatar
  Subscribe  
Notify of