Splunk Search
Highlighted

How to write a Splunk search to group a few lines before and after a matching event?

New Member

Hello,

I need your help in making a search where I can group lines before and after a matching event in Splunk, same as this UNIX command:

grep -C 2 <string> <filename>

Thanks... !!!

0 Karma
Highlighted

Re: How to write a Splunk search to group a few lines before and after a matching event?

Esteemed Legend

Like this (with autoregress command):

... <string> | autoregress _raw AS PrevEventsp=1-3

http://docs.splunk.com/Documentation/Splunk/6.3.0/SearchReference/Autoregress

This can also can be done with streamstats.

0 Karma
Highlighted

Re: How to write a Splunk search to group a few lines before and after a matching event?

SplunkTrust
SplunkTrust

Sorry to bring bad news, but this does not work:

Error in 'autoregress' command: You cannot specify new field name when you specify a range for 'p'.

Also remember this will only work if you don't use a filter in the base search otherwise autoregress has only _raw events containing the filter and nothing else.

0 Karma
Highlighted

Re: How to write a Splunk search to group a few lines before and after a matching event?

Esteemed Legend

@MuS is correct (that is what I get for not testing); the command should actually be:

... <string> | eval raw=_raw | autoregress raw p=1-3

He is also correct that this will only bring in the previous matching events, not the events before the match. So you would actually have to do it like this:

... <base search that includes all events> | eval raw=_raw | autoregress raw p=1-3 | search <string>

This could be quicker than using map, but it really depends on how many matches you have and how many events are in your base search.

0 Karma
Highlighted

Re: How to write a Splunk search to group a few lines before and after a matching event?

SplunkTrust
SplunkTrust

Hi ProudDevil,

you can use map to get those events; take this run everywhere search which will search index=_internal for kbps values over 35 in metrics.log and will return the surrounding events from sourcetype=splunkd, starting 2.5 minutes before the event and ending 2.5 minutes after the event:

index=_internal source="*metrics.log" kbps>35 
| eval start_time=_time-150 
| eval end_time=start_time+150 
| map search="search index=_internal sourcetype=splunkd earliest=$start_time$ latest=$end_time$"

you can change the map search to return events for the kbps and the surrounding events as well:

index=_internal source="*metrics.log" kbps>35 
| eval start_time=_time-150 
| eval end_time=start_time+150 
| map search="search index=_internal source="*metrics.log" earliest=$start_time$ latest=$end_time$"

Hope this helps to get you started ...

cheers, MuS