Ratting Gergely Show surrounding rows with grep

After I grep for errors in syslog, the next step is almost always grep for the time like grep "12:31:1" so I can look at the surrounding logs. Here is a better way to do that.

For example if I look for "Could not initialize TLS" errors in syslog, I go

cat /var/log/syslog | grep "Could not initialize TLS"

which results in

Apr 21 13:33:12 ldap-ng slapd[12740]: conn=111133 op=0 RESULT oid= err=52 text=Could not initialize TLS
Apr 21 13:35:14 ldap-ng slapd[12740]: conn=111172 op=0 RESULT oid= err=52 text=Could not initialize TLS

Then I grep on the time or on the connection id if there is one:

cat /var/log/syslog | grep "conn=111172" or cat /var/log/syslog | grep "13:35:1"

which then results in

Apr 21 13:33:12 ldap-ng slapd[12740]: conn=117386 fd=19 ACCEPT from IP=192.168.1.67:45948 (IP=0.0.0.0:389)
Apr 21 13:33:12 ldap-ng slapd[12740]: conn=117386 op=0 EXT oid=1.3.6.1.4.1.1466.20037
Apr 21 13:33:12 ldap-ng slapd[12740]: conn=117386 op=0 STARTTLS
Apr 21 13:33:12 ldap-ng slapd[12740]: conn=117386 op=0 RESULT oid= err=52 text=Could not initialize TLS

The downside of this is that I have to do this one by one. It turns out that there are some grep flags that helps. Running cat /var/log/syslog | grep -B 3 "Could not initialize TLS" returns:

Apr 21 13:33:12 ldap-ng slapd[12740]: conn=117386 fd=19 ACCEPT from IP=192.168.1.67:45948 (IP=0.0.0.0:389)
Apr 21 13:33:12 ldap-ng slapd[12740]: conn=117386 op=0 EXT oid=1.3.6.1.4.1.1466.20037
Apr 21 13:33:12 ldap-ng slapd[12740]: conn=117386 op=0 STARTTLS
Apr 21 13:33:12 ldap-ng slapd[12740]: conn=117386 op=0 RESULT oid= err=52 text=Could not initialize TLS
--
Apr 21 13:35:14 ldap-ng slapd[12740]: conn=117398 fd=19 ACCEPT from IP=192.168.1.67:45962 (IP=0.0.0.0:389)
Apr 21 13:35:14 ldap-ng slapd[12740]: conn=117398 op=0 EXT oid=1.3.6.1.4.1.1466.20037
Apr 21 13:35:14 ldap-ng slapd[12740]: conn=117398 op=0 STARTTLS
Apr 21 13:35:14 ldap-ng slapd[12740]: conn=117398 op=0 RESULT oid= err=52 text=Could not initialize TLS

As you see grep -B 3 returns the result with the 3 rows before it, for every match. Two more useful flags are -A 3 that returns 3 rows after the match, and -C 3 which returns 3 before and 3 after it.