Splunk Search

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

ProudDevil
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

MuS
Legend

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

woodcock
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

MuS
Legend

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

woodcock
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
Get Updates on the Splunk Community!

Built-in Service Level Objectives Management to Bridge the Gap Between Service & ...

Wednesday, May 29, 2024  |  11AM PST / 2PM ESTRegister now and join us to learn more about how you can ...

Get Your Exclusive Splunk Certified Cybersecurity Defense Engineer Certification at ...

We’re excited to announce a new Splunk certification exam being released at .conf24! If you’re headed to Vegas ...

Share Your Ideas & Meet the Lantern team at .Conf! Plus All of This Month’s New ...

Splunk Lantern is Splunk’s customer success center that provides advice from Splunk experts on valuable data ...