grep/display number of lines before and after matching a pattern

I know lots of people are looking for a command-line method on grepping a particular line and some lines BEFORE OR AFTER that pattern matched line….

There are atleast 2 ways which I know :)..

Method 1 : using GREP

I think it will be self explanatory by the below example…

[hchiramm@hchiramm tmp]$ cat /etc/sysconfig/network-scripts/ifcfg-eth0
# Networking Interface
DEVICE=eth0
BOOTPROTO=dhcp
HWADDR=00:24:E8:9A:5F:56
ONBOOT=yes
BRIDGE=br0
[hchiramm@hchiramm tmp]$ cat /etc/sysconfig/network-scripts/ifcfg-eth0 |grep -A 3 Networking
# Networking Interface
DEVICE=eth0
BOOTPROTO=dhcp
HWADDR=00:24:E8:9A:5F:56
[hchiramm@hchiramm tmp]$ cat /etc/sysconfig/network-scripts/ifcfg-eth0 |grep -B 2 HWADDR
DEVICE=eth0
BOOTPROTO=dhcp
HWADDR=00:24:E8:9A:5F:56
[hchiramm@hchiramm tmp]$

Here “A” stands for “AFTER” and “B” stands for “BEFORE”.. The numeric value in “grep” command is the number of lines you want to display..

Method 2: Using “sed” command..

[hchiramm@hchiramm tmp]$ sed -n ‘/Networ/{p;n;p;n;p;n;p;n;p;n;p;n;p;n;p}’ /etc/sysconfig/network-scripts/ifcfg-eth0
# Networking Interface
DEVICE=eth0
BOOTPROTO=dhcp
HWADDR=00:24:E8:9A:5F:56
ONBOOT=yes
BRIDGE=br0
[hchiramm@hchiramm tmp]$ sed -n ‘/Networ/{p;n;p;n;p;n;p;n;p}’ /etc/sysconfig/network-scripts/ifcfg-eth0
# Networking Interface
DEVICE=eth0
BOOTPROTO=dhcp
HWADDR=00:24:E8:9A:5F:56
ONBOOT=yes
[hchiramm@hchiramm tmp]$ sed -n ‘/Networ/{p;n;p;n;p;n;p}’ /etc/sysconfig/network-scripts/ifcfg-eth0
# Networking Interface
DEVICE=eth0
BOOTPROTO=dhcp
HWADDR=00:24:E8:9A:5F:56
[hchiramm@hchiramm tmp]$

thats it 🙂

2 Replies to “grep/display number of lines before and after matching a pattern”

Leave a Reply

Your email address will not be published. Required fields are marked *