Splunk Search

{} equivalent on right hand side of eval

usd0872
Path Finder

I hate hardcoding dynamic things. Sooner or later those thing break. I have data with fields

 

... forecast_2020=400, forecast_2021=500, forecast_2022=650, forecast_2023=800 ...

 

and in some search I need to use the correct forecast for the current year.

What I could do is

 

...
| eval year=strftime(now(),"%Y"),
       forecast=case(year==2021, forecast_2021,
                     year==2022, forecast_2022,
                     year==2023, forecast_2023,
                     1==1,       0)

 

This definitely results in problems in 2024; by then I will have a field forecast_2024 but nobody will remember to update the search.

I'd rather use something along these lines:

 

...
| eval year=strftime(now(),"%Y"),
       forecast=coalesce(forecast_{year}, 0)

 

However, the {} trick can only be used on the left hand side in eval. Is there any similar cool trick which works on the right hand side?

Labels (2)
0 Karma
1 Solution

ITWhisperer
SplunkTrust
SplunkTrust

Not exactly since it still uses {} on the left, but using foreach you could do this

| makeresults 
| eval year=strftime(now(),"%Y")
| eval forecast_2021=random()%100


| eval year_{year}=year
| foreach year_*
    [| eval forecast=coalesce(forecast_<<MATCHSTR>>,0)]

View solution in original post

0 Karma

PickleRick
SplunkTrust
SplunkTrust

Ugly but should work. Use foreach.

For example:

| makeresults count=3
| eval a1=2,a2=5,a3=8
| streamstats count
| foreach a*
[ eval result=if (<<MATCHSTR>> = count,<<FIELD>>,result)]

 Adjust to your needs (make the condition reference current year) and you're good to go.

0 Karma

usd0872
Path Finder

Yep, foreach is the way to solve this. Thank you.

0 Karma

ITWhisperer
SplunkTrust
SplunkTrust

Not exactly since it still uses {} on the left, but using foreach you could do this

| makeresults 
| eval year=strftime(now(),"%Y")
| eval forecast_2021=random()%100


| eval year_{year}=year
| foreach year_*
    [| eval forecast=coalesce(forecast_<<MATCHSTR>>,0)]
0 Karma

usd0872
Path Finder

Bingo! A good way to achieve the result. It fits my need perfectly, I just could not think of it myself. Thank you.

0 Karma
Career Survey
First 500 qualified respondents will receive a $20 gift card! Tell us about your professional Splunk journey.

Can’t make it to .conf25? Join us online!

Get Updates on the Splunk Community!

Can’t Make It to Boston? Stream .conf25 and Learn with Haya Husain

Boston may be buzzing this September with Splunk University and .conf25, but you don’t have to pack a bag to ...

Splunk Lantern’s Guide to The Most Popular .conf25 Sessions

Splunk Lantern is a Splunk customer success center that provides advice from Splunk experts on valuable data ...

Unlock What’s Next: The Splunk Cloud Platform at .conf25

In just a few days, Boston will be buzzing as the Splunk team and thousands of community members come together ...