Splunk Search

Can you explain the syntax of the foreach command beyond what's in the Docs?

Path Finder

Hi,

I'm trying to understand the syntax of foreach, I've had a look at the documentation, but it's just too difficult for me to understand and the examples aren't great.

I would really appreciate if someone can explain to me how to use the foreach command as well as the syntax.

Moreover, the reason why I want to use a foreach is because I have a list of data that I need to loop through pull out data for a particular field.

Labels (1)
0 Karma

Esteemed Legend

There are 2 "looping" commands. The map command loops over rows (events) whereas the foreach command loops over columns (fields). It really is that simple.

0 Karma

Motivator

It's a bit more complicated than that.

map creates new searches from the results of each row that entirely replace the results of the host search.

foreach allows you to use segments from each column name to construct an eval that adds to or changes the host search results.

0 Karma

Revered Legend

Foreach can be read as "foreach specified fields..perform this eval..". It performs an eval expression on all matching fields and does it for all the rows.

...| foreach ...column list... [ eval-expression using template representation]

Map can be read as "foreach rows in my result,..run this search". It initiates a search for each row of the search result that comes before map command. It would be better if you can provide your detailed requirement, with current and expected output.

0 Karma

Legend

@mahbs, foreach is like a template for eval and its use case is where you might have the need to perform several similar evals. It is quite powerful command with plenty of use cases, if used aptly. So, it would be be better if you provide some insight to what you are trying to achieve, so that we provide example/explanation for the same.

____________________________________________
| makeresults | eval message= "Happy Splunking!!!"
0 Karma

SplunkTrust
SplunkTrust

You should look into the map command which does a foreach

index=xxx ... 
| map search="search sourcetype="xxxx" val=$val$|stats values(sessionid) by val"

Map is like a foreach iterator. It will take each "result" of a previous search, and perform the map search that many times with the specified map search.

0 Karma

Path Finder

Ok, I need the iterator aspect of the map. Is map like a subsearch? Because that's not what I need

0 Karma

SplunkTrust
SplunkTrust

Map will iterate based on each condition, just like a foreach loop will do. The iterator aspect will iterate over each value until there is no values left.

0 Karma

Influencer

The synatx is complex - what are you actually trying to do? Can you provide some event samples?

0 Karma