Splunk foreach command examples

The Splunk foreach SPL command is pretty useful for building powerful queries. Here are some examples that I’ve created as a reference for how to use this powerful command.

The first example demonstrates MATCHSEG1. This can be used to construct a new field (matchseg1_field) from the part of the field name that matched the wildcard (field_*). The double quotes are required ("<<MATCHSEG1>>").

| makeresults count=1  
| eval field_a="foo", field_b="bar", field_c="baz"  
| eval matchseg1_field=""  
| foreach field_*  
    [ eval matchseg1_field=matchseg1_field + "<<MATCHSEG1>>" ]

This example demonstrates how to overwrite fields, for example, to round the results of a stats calculation.

| makeresults count=2  
| eval foo=random()  
| stats stdev(foo)  
| foreach stdev(*)  
    [ eval <<FIELD>>=round('<<FIELD>>',0)]

I’ll add more examples soon, maybe!