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!

Introducing the 2024 SplunkTrust!

Hello, Splunk Community! We are beyond thrilled to announce our newest group of SplunkTrust members!  The ...

Introducing the 2024 Splunk MVPs!

We are excited to announce the 2024 cohort of the Splunk MVP program. Splunk MVPs are passionate members of ...

Splunk Custom Visualizations App End of Life

The Splunk Custom Visualizations apps End of Life for SimpleXML will reach end of support on Dec 21, 2024, ...