Splunk Search

foreach with more than one FIELD?

hriazi
Engager

Hello,
In the code below, the first foreach sums the values in field A, and returns 21 (5+3+2+6+1+4=21).
The second foreach counts the number of B field that has a value of 1, and it returns 4 (for B1,B2,B3,B6).

|makeresults 1
| eval Selected_As_Total =0
| eval A1=5 | eval A2=3 | eval A3=2 | eval A4=6 | eval A5=1 | eval A6=4 | eval B1=1 | eval B2=1 | eval B3=1 | eval B4=2 | eval B5=2 | eval B6=1

| foreach A* [eval Selected_As_Total = Selected_As_Total + <>]

| eval Selected_Bs_Count = 0
| foreach B* [ eval Selected_Bs_Count = Selected_Bs_Count + case(<>=1,1,1=1,0)]

Question/problem: I need to get the total only for those A fields that their corresponding B field has a value of 1.
So the in this example we would select A1=5,A2=3,A3=2,A6=4 because B1=1,B2=1,B3=1,B6=1, and the result would come to 5+3+2+4=14.

How do I do that? Is there a way to combine these two foreach commands into one? In other words, is there way to have a foreach with two FIELDs?
Is there another way to accomplish what I need?

BTW, in each event there is a B field for every A field, but the number of A/B pairs could be different from one event to the next.

I have searched the docs and Q/As and have not found a similar case. Thank you for any help you could offer.

0 Karma
1 Solution

richgalloway
SplunkTrust
SplunkTrust

Try this

| foreach A* [eval Selected_As_Total = Selected_As_Total + if(B<<MATCHSTR>>=1, <<FIELD>>,0)]
---
If this reply helps you, Karma would be appreciated.

View solution in original post

0 Karma

richgalloway
SplunkTrust
SplunkTrust

Try this

| foreach A* [eval Selected_As_Total = Selected_As_Total + if(B<<MATCHSTR>>=1, <<FIELD>>,0)]
---
If this reply helps you, Karma would be appreciated.
0 Karma

hriazi
Engager

Thank you Rich. It works beautifully. Now I understand what the MATCHSTR does.

0 Karma
Got questions? Get answers!

Join the Splunk Community Slack to learn, troubleshoot, and make connections with fellow Splunk practitioners in real time!

Meet up IRL or virtually!

Join Splunk User Groups to connect and learn in-person by region or remotely by topic or industry.

Get Updates on the Splunk Community!

Announcing Modern Navigation: A New Era of Splunk User Experience

We are excited to introduce the Modern Navigation feature in the Splunk Platform, available to both cloud and ...

Modernize your Splunk Apps – Introducing Python 3.13 in Splunk

We are excited to announce that the upcoming releases of Splunk Enterprise 10.2.x and Splunk Cloud Platform ...

Step into “Hunt the Insider: An Splunk ES Premier Mystery” to catch a cybercriminal ...

After a whole week of being on call, you fell asleep on your keyboard, and you hit a sequence of buttons that ...