How to grep some content with before and after lines in linux and AIX ?

Today in this article we will look how to search a paragraph like content, or say get some lines before the searched text and few lines afterwards.

In linux, we are provided with more flexible options to get the number of lines before and after the text as per our own convenience.

I. Linux: Getting lines before and after the searched term

### In normal grep case
[root@ngelinux01 ]# cat dhcpd.conf | grep 10.56.195.0
subnet 10.56.195.0 netmask 255.255.255.0 {
[root@ngelinux01 ]#

### when we use the options with grep
[root@ngelinux01 ]# cat dhcpd.conf | grep -iA5 -B1 10.56.195.0

subnet 10.56.195.0 netmask 255.255.255.0 {​​​​​​​

  option subnet-mask 255.255.255.0;
  option routers 10.56.195.3;
  option domain-search "get.ngelinux.com";
}​​​​​​​

Here we have used below two options:
1. “-A5” to get 5 lines after the searched text.
2. “-B1″ to get 1 line before the searched text.

 

II. AIX: KSH: Getting set of text connected with searched text.

### In general case
ngeaix01 saket $ cat /etc/filesystems | grep -i devWEB
/usr/devWEB:
        dev             = /dev/devWEBlv
/usr/devWEB/WEB/stdlist:
        dev             = /dev/devWEBstdlv

### After using "-p" option
ngeaix01 saket $ cat /etc/filesystems | grep -ip devWEB
/usr/devWEB:
        dev             = /dev/devWEBlv
        vfs             = jfs2
        log             = /dev/hd8
        mount           = true
        account         = false


/usr/devWEB/WEB/stdlist:
        dev             = /dev/devWEBstdlv
        vfs             = jfs2
        log             = /dev/hd8
        mount           = true
        account         = false
ngeaix01 saket $

In above example, we can see the use of option “-p” to get the complete paragraph in output.

In AIX, we don’t have “-A” and “-B” options available to use, we use -p option to get the complete text.

Leave a Reply

Your email address will not be published.