Splunk Search

rex expression without resorting to mode=sed

avalon
Explorer

Hi!

I am changing a string in the host field of output with this format

ZX3B1093200198A
ZX3B1093200198B

The last alpha character is either 'A' or 'B'
(with that some might be able to guess what the platform is)

I can do precisely that with a simple sed

index=relevant index name sourcetype=relevant source type | rex mode=sed field=host "s/[A-B]$//"

That, not surprisingly, works. But I would like to do the same with rex, but without resorting to sed, which doesn't get used elsewhere.

This works;

index=relevant index name sourcetype=relevant source type | rex field=host "(?<host>.*).{1}"

But I want to specify that only the characters 'A' or 'B' (always uppercase) are removed if present.

I tried (?<host>.*[A,B]).{1} and a few other similar combinations but can't achieve that very last bit.

Any pointers or assistance gratefully received!

Tags (3)
0 Karma

somesoni2
Revered Legend

Firstly, I do agree with @echalex about best way for this requirement is to use rex with sed.

Keeping your requirement of removing 'A' or 'B' from last part to be removed, if present, try one of following options (run anywhere sample, added rex-sed example as well for comparison)

|gentimes start=-1 | eval host="ZX3B1093200198A ZX3B1093200198B ZX3B1093200198" | table host | makemv host | mvexpand host | eval host1=host 
| rex mode=sed field=host1 "s/[A-B]$//" 
| rex field=host "(?<host2>.*[^AB])" 
| eval host3=replace(host,"((\w+\d+)*)([AB])$","\1") 
| eval host4=rtrim(host,"AB")

avalon
Explorer

Great answer! Nice to see all of the options available.

echalex
Builder

Hi,
I'm not sure why you want to avoid mode=sed. It seems like the correct way. In any case, if you do want to avoid it, the following should do the trick of recognising an A or B at the end:

rex field=host "(?<host>.*)[A,B]$"

HTH

avalon
Explorer

Terrific!
All for the need of a bracket in the right place!

The sed routine really looks the most efficient!

Got questions? Get answers!

Join the Splunk Community Slack to learn, troubleshoot, and make connections with fellow Splunk practitioners in real time!

Meet up IRL or virtually!

Join Splunk User Groups to connect and learn in-person by region or remotely by topic or industry.

Get Updates on the Splunk Community!

Kick the Tires Before You Commit: A Hands-On Tour of the Splunk Observability Cloud ...

Evaluating an enterprise observability platform usually goes like this: fill out a form, get a free trial with ...

Deep insights, no barriers: Splunk Observability Cloud Free Edition

As software delivery cycles continue to accelerate, observability shouldn’t be a luxury — it should be a ...

Monitoring AI Agents with Splunk Observability Cloud

Let’s say I’m running a travel planning AI app in production. A user asks for three concise hotel options in ...