How to Grep Multiples Lines and using Specific Keyword on Linux

grep is a command line text search utility originally written for Unix or linux. In linux you can grep multiple lines before or after matching the keywords. This examples has been tested on linux CentOS 6.2, but it may workings on other linux version such as Redhat Enterprise Linux 5 (RHEL5) or (RHEL6).

Get grep command help :

[root@centos62 ~]# grep --help

Example :

Context control:
  -B, --before-context=NUM  print NUM lines of leading context
  -A, --after-context=NUM   print NUM lines of trailing context
  -C, --context=NUM         print NUM lines of output context
  -NUM                      same as --context=NUM

Assumed that you have exported all log for 29 March 2012 from /var/log/messages into 29032012.txt as below :

[root@centos62 ~]# more /var/log/messages | grep "Mar 29" > 29032012.txt

1. How to Grep Multiples Lines

Please grep “cubic” with -B1 and -A4 :

[root@centos62 ~]# grep -B1 -A4 "cubic" 29032012.txt

The output will return like this :

Mar 29 21:04:16 centos62 kernel: usbhid: v2.6:USB HID core driver
Mar 29 21:04:16 centos62 kernel: TCP cubic registered
Mar 29 21:04:16 centos62 kernel: Initializing XFRM netlink socket
Mar 29 21:04:16 centos62 kernel: NET: Registered protocol family 17
Mar 29 21:04:16 centos62 kernel: Using IPI No-Shortcut mode
Mar 29 21:04:16 centos62 kernel: registered taskstats version 1

2. How to Grep using Specific Keyword :
Grep only keyword “BIOS-e820” from 29032012.txt file as below :

[root@centos62 ~]# more 29032012.txt | grep "BIOS-e820"

The output will return like this :

Mar 29 21:04:16 centos62 kernel: BIOS-e820: 0000000000000000 - 000000000009f800 (usable)
Mar 29 21:04:16 centos62 kernel: BIOS-e820: 000000000009f800 - 00000000000a0000 (reserved)
Mar 29 21:04:16 centos62 kernel: BIOS-e820: 00000000000ca000 - 00000000000cc000 (reserved)
Mar 29 21:04:16 centos62 kernel: BIOS-e820: 00000000000dc000 - 00000000000e0000 (reserved)
Mar 29 21:04:16 centos62 kernel: BIOS-e820: 00000000000e4000 - 0000000000100000 (reserved)
Mar 29 21:04:16 centos62 kernel: BIOS-e820: 0000000000100000 - 000000003fef0000 (usable)
Mar 29 21:04:16 centos62 kernel: BIOS-e820: 000000003fef0000 - 000000003feff000 (ACPI data)
Mar 29 21:04:16 centos62 kernel: BIOS-e820: 000000003feff000 - 000000003ff00000 (ACPI NVS)
Mar 29 21:04:16 centos62 kernel: BIOS-e820: 000000003ff00000 - 0000000040000000 (usable)
Mar 29 21:04:16 centos62 kernel: BIOS-e820: 00000000e0000000 - 00000000f0000000 (reserved)
Mar 29 21:04:16 centos62 kernel: BIOS-e820: 00000000fec00000 - 00000000fec10000 (reserved)
Mar 29 21:04:16 centos62 kernel: BIOS-e820: 00000000fee00000 - 00000000fee01000 (reserved)
Mar 29 21:04:16 centos62 kernel: BIOS-e820: 00000000fffe0000 - 0000000100000000 (reserved)