contextual data with grep

If you need to print a certain number of lines before and/or a pattern match, grep can achieve this with the -B{number} and -A{number} options. This can be very useful when looking through logs and trying to determine what events took place immediately before and/or after the event in question.

For instance,

[root@yogi ~]# grep -B4 -A4 -i xinetd /var/log/messages | tail -15
Mar 12 15:18:31 yogi yum[6531]: Installed: kernel-2.6.32-504.8.1.el6.x86_64
Mar 12 15:19:22 yogi init: console main process (868) killed by TERM signal
Mar 12 15:19:22 yogi init: tty2 main process (869) killed by TERM signal
Mar 12 15:19:22 yogi saslauthd[765]: server_exit     : master exited: 765
Mar 12 15:19:28 yogi xinetd[589]: Exiting...
Mar 12 15:19:28 yogi kernel: Kernel logging (proc) stopped.
Mar 12 15:19:28 yogi rsyslogd: [origin software="rsyslogd" swVersion="5.8.10" x-pid="559" x-info="http://www.rsyslog.com"] exiting on signal 15.
Mar 12 15:19:35 yogi kernel: imklog 5.8.10, log source = /proc/kmsg started.
Mar 12 15:19:35 yogi rsyslogd: [origin software="rsyslogd" swVersion="5.8.10" x-pid="567" x-info="http://www.rsyslog.com"] start
Mar 12 15:19:35 yogi xinetd[600]: xinetd Version 2.3.14 started with libwrap loadavg labeled-networking options compiled in.
Mar 12 15:19:35 yogi xinetd[600]: Started working: 0 available services
Mar 12 15:19:36 yogi saslauthd[779]: detach_tty      : master pid is: 779
Mar 12 15:19:36 yogi saslauthd[779]: ipc_init        : listening on socket: /var/run/saslauthd/mux
Mar 12 15:59:01 yogi yum[1199]: Installed: 1:grub-0.97-93.el6.x86_64
Mar 13 05:06:24 yogi yum[10927]: Installed: freetype-2.3.11-14.el6_3.1.x86_64