Splunk Search

How. to replace string if preceded or followed by particular characters?

firstname
Explorer

Given the below example events:

Initial event:

[stuff] apple.bean.carrot2donut.57.egg.fish(10) max:311 min 15 avg 101 low:1[stuff]

Result event 1:

[stuff] apple.bean.carrot&donut.&.egg.fish(&) max:& min & avg & low:&[stuff]

Result event 2:

[stuff] apple.bean.carrot2donut.57.egg.fish(&) max:& min & avg & low:&[stuff]

I want to get Result 2 rather than Result 1.  I want to replace any series of numbers with an ampersand only if one of three conditions are true.  These conditions:

  1. The number series is preceded by a space.
  2. The number series is preceded by a colon.
  3. The number series is preceded by an open parenthesis and followed by a closed parenthesis.

If I use the replace line below, the new variable created will contain Result 1 rather than the Result 2 I desire.

| eval event = replace(_raw, "[0-9]+", "&")

How do I get Result 2 instead?

Labels (2)
0 Karma
1 Solution

ITWhisperer
SplunkTrust
SplunkTrust

 

| rex mode=sed "s/(?<a>\s|\:)(?<b>\d+)/\1\&/g s/\(\d+\)/(\&)/g"

 

View solution in original post

ITWhisperer
SplunkTrust
SplunkTrust

 

| rex mode=sed "s/(?<a>\s|\:)(?<b>\d+)/\1\&/g s/\(\d+\)/(\&)/g"

 

firstname
Explorer

I think this is almost correct.  It doesn't seem to catch the parentheses condition.  I've tried to omit a closing parenthesis

| rex mode=sed "s/(?<a>\s|\:|\((?<b>\d+)/\1\&/g"

However, Splunk will not allow this search without the closing parenthesis.  I see how this is used to have "or" conditions, but is it possible to use such conditions to allow the stated parentheses condition?

0 Karma

ITWhisperer
SplunkTrust
SplunkTrust

Updated solution - essentially you would need to do two substitutions, but these can be done in the same rex

0 Karma

gcusello
SplunkTrust
SplunkTrust

Hi @firstname,

please try with a regex like the following:

| makeresults | eval my_field="[stuff] apple.bean.carrot2donut.57.egg.fish(10) max:311 min 15 [stuff]"
| append [ | makeresults | eval my_field="[stuff] apple.bean.carrot&donut.&.egg.fish(&) max:& min & [stuff]"]
| append [ | makeresults | eval my_field="[stuff] apple.bean.carrot2donut.57.egg.fish(&) max:& min & [stuff]"]
| rex field=my_field mode=sed "s/(\d+)/(\&)/g"

Ciao.

Giuseppe

Get Updates on the Splunk Community!

Leveraging Automated Threat Analysis Across the Splunk Ecosystem

Enhance Security Operations with Automated Threat Analysis in the Splunk EcosystemAre you leveraging ...

Splunk Developers: Go Beyond the Dashboard with These .Conf25 Sessions

  Whether you’re building custom apps, diving into SPL2, or integrating AI and machine learning into your ...

Index This | How do you write 23 only using the number 2?

July 2025 Edition Hayyy Splunk Education Enthusiasts and the Eternally Curious!  We’re back with this month’s ...