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

Detecting Brute Force Account Takeover Fraud with Splunk

This article is the second in a three-part series exploring advanced fraud detection techniques using Splunk. ...

Buttercup Games: Further Dashboarding Techniques (Part 9)

This series of blogs assumes you have already completed the Splunk Enterprise Search Tutorial as it uses the ...

Buttercup Games: Further Dashboarding Techniques (Part 8)

This series of blogs assumes you have already completed the Splunk Enterprise Search Tutorial as it uses the ...