Splunk SPL Commands

What Is the foreach Command?

The foreach command iterates over a list of fields and applies the same SPL operation to each one. It eliminates the need to write repetitive eval statements when you need to transform, threshold, or format multiple fields identically.

Core Syntax

| foreach <field-list-or-wildcard> [eval <<FIELD>> = <expression_using_<<FIELD>>>]

Use <<FIELD>> as a placeholder for the current field name in each iteration.

Security Operations Examples

1. Convert Multiple Byte Fields to MB

index=network sourcetype=firewall
| stats sum(bytes_in) AS bytes_in sum(bytes_out) AS bytes_out sum(bytes_total) AS bytes_total BY src_ip
| foreach bytes_* [eval <<FIELD>> = round('<<FIELD>>' / 1048576, 2)]
| rename bytes_in AS MB_in bytes_out AS MB_out bytes_total AS MB_total

2. Apply Threshold Flags Across Severity Columns

index=vulnerability sourcetype=qualys
| chart count OVER dest_ip BY severity
| foreach Critical High Medium Low [eval <<FIELD>>_flag = if('<<FIELD>>' > 10, "ALERT", "OK")]

3. Null Cleanup Across All Fields

| foreach * [eval <<FIELD>> = if(isnull('<<FIELD>>'), "N/A", '<<FIELD>>')]

4. Percentage Calculation for Timechart Results

index=security sourcetype=WinEventLog:Security
| timechart span=1d count BY EventCode limit=5
| addtotals
| foreach 4624 4625 4648 4672 4688 [eval <<FIELD>>_pct = round('<<FIELD>>' / Total * 100, 1)]

Wildcard Patterns

| foreach bytes_*    → Matches bytes_in, bytes_out, etc.
| foreach *_count    → Matches error_count, success_count, etc.
| foreach *          → All fields (use with caution)

Advanced: Nested Operations

| foreach avg_* [eval <<FIELD>>_zscore = ('<<FIELD>>' - 'mean_<<FIELD>>') / 'stdev_<<FIELD>>']

Best Practices

  • Use wildcards to target field groupsbytes_*, count_*, *_score patterns keep your searches clean and scalable.
  • Quote field references — Use '<<FIELD>>' (single-quoted) to reference the field’s value within eval.
  • Avoid foreach * on large datasets — Iterating over all fields can be expensive. Be specific.
  • Test with a small subset first — Use | head 10 before foreach to validate your logic.

Next in the series: Splunk’s Common Information Model (CIM) — the framework that ties it all together.


Next in the Rhombic SPL Series → Splunk Common Information Model (CIM)