How to grep a particular line using sed in linux ?

In this post, we will look how to use sed command to grep a particular line in Linux.

This is one of the most used command in our day to day activities.

1. Get specific line from a file.

### Getting 5th line from /etc/passwd file.
[root@nglinux ~]# sed -n 5p /etc/passwd
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
[root@nglinux ~]# 

2. Grep specific line from a command output.

### Display 3rd line ouput
[root@nglinux ~]# top -bn1 -d1 | sed -n '3p'
Cpu(s):  0.2%us,  0.3%sy,  0.0%ni, 99.3%id,  0.1%wa,  0.0%hi,  0.1%si,  0.0%st
[root@nglinux ~]# 

3. Grep range of lines.

### Display 5 lines from 1 to 5.
[root@nglinux ~]#  top -bn1 -d1 | sed -n '1,5p'
top - 07:32:33 up 4 days, 13:44,  4 users,  load average: 0.00, 0.00, 0.00
Tasks: 153 total,   1 running, 152 sleeping,   0 stopped,   0 zombie
Cpu(s):  0.2%us,  0.3%sy,  0.0%ni, 99.3%id,  0.1%wa,  0.0%hi,  0.1%si,  0.0%st
Mem:   1030316k total,   734816k used,   295500k free,   158792k buffers
Swap:        0k total,        0k used,        0k free,   358932k cached
[root@nglinux ~]# 

4. Display last line using sed.

### Display last line of /etc/passwd file.
[root@nglinux ~]# sed -n \$p /etc/passwd
saket:x:501:501::/home/saket:/bin/bash

### Verify last line using tail command.
[root@nglinux ~]# tail -1 /etc/passwd
saket:x:501:501::/home/saket:/bin/bash
[root@nglinux ~]# 

Make a note of this sed command and use it whenever required to grep specific line from a file.

Do post your comments, or suggestions below.

Leave a Reply

Your email address will not be published.