Splunk Search

## foreach with more than one FIELD?

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.

Tags (2)
1 Solution
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.
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.
Engager

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

Get Updates on the Splunk Community!