Splunk Search

How to use variable within foreach command?

sats2020
New Member

I'm looping through JSON array and compare each value using a temporary variable but due to some reason the temporary variable is not getting set when I iterate the JSON array.

Please find the code snippet below

index="snow_incident"
| head 1 
| spath path=result{} output=x
| fields - _raw
| mvexpand x
| spath input=x
| eval major_inc_temp = ""
| foreach x [eval Uptime = if(match(major_inc_temp,u_major_incident),"100","200")
| eval major_inc_temp = u_major_incident] | table major_inc_temp,Uptime, cmdb_ci

Please do let me know how do I address this problem

0 Karma

lguinn2
Legend

The foreach command iterates over a set of fields - not events. So if I had 6 fields with names that all started with Percent, I could use the foreach command to do the same set of actions for each field Percent*.

You don't specify iteration in Splunk like in programming languages. In fact, you generally don't specify iteration at all.

I suspect that what you want is quite different. You have a set of events and you want to calculate a few field for the various subsets of events. Try something like this:

index="snow_incident"
| head 1 
| spath path=result{} output=x
| fields - _raw
| mvexpand x
| spath input=x
| eval Uptime = if(match(major_inc_temp,u_major_incident),"100","200")
| eval major_inc_temp = u_major_incident
| table major_inc_temp, Uptime, cmdb_ci

The next question is: what do you want to accomplish? Are you trying to find a maximum of something? More info would really be helpful.

0 Karma
Get Updates on the Splunk Community!

Updated Data Type Articles, Anniversary Celebrations, and More on Splunk Lantern

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

A Prelude to .conf25: Your Guide to Splunk University

Heading to Boston this September for .conf25? Get a jumpstart by arriving a few days early for Splunk ...

4 Ways the Splunk Community Helps You Prepare for .conf25

.conf25 is right around the corner, and whether you’re a first-time attendee or a seasoned Splunker, the ...