Splunk Search
Highlighted

How do I reverse/swap characters in a string value returned from a search?

Explorer

Hi,

If my search returns a string value of "ABCDEF"

1) How do I modify the search to reverse this value so it outputs "FEDCBA" ?

2) How do I swap characters from this value so it outputs "BADCFE" ? (1st 2 characters are being swapped)

Thanks!

Highlighted

Re: How do I reverse/swap characters in a string value returned from a search?

Esteemed Legend

This does just the first 2:

... | rex field=myField mode=sed "s/(.)(.)/\2\1/" | table host

Extend the example (more (.) in the first section and more \# in the second section) to reverse longer strings.

This byteswaps an entire string of any length (every pair):

... | rex field=myField mode=sed "s/(.)(.)/\2\1/g" | table host

View solution in original post

Highlighted

Re: How do I reverse/swap characters in a string value returned from a search?

SplunkTrust
SplunkTrust

I would suggest one correction to add "g" flag in the end to do it for all characters. like s/(.)(.)/\2\1/g

Highlighted

Re: How do I reverse/swap characters in a string value returned from a search?

Explorer

ha perfect that worked. thank you both!

Highlighted

Re: How do I reverse/swap characters in a string value returned from a search?

SplunkTrust
SplunkTrust

Don't forget to accept the answer by clicking on the Accept hyperlink below the answer.

0 Karma
Highlighted

Re: How do I reverse/swap characters in a string value returned from a search?

SplunkTrust
SplunkTrust

Sorry guys, but this is one of the sweetest regex ever on answers! 🙂

Highlighted

Re: How do I reverse/swap characters in a string value returned from a search?

Esteemed Legend

OK @MuS, cough up some up-vote love!

0 Karma
Highlighted

Re: How do I reverse/swap characters in a string value returned from a search?

Explorer

Hey thanks I just ran what you mentioned but its only swapping the first 2 characters.

Value to swap = 535276

Swapped value 355276

Changing the lengths doesnt seem to work?

0 Karma
Highlighted

Re: How do I reverse/swap characters in a string value returned from a search?

SplunkTrust
SplunkTrust

Did you add the 'g' in the end as mentioed in the comment? Try this runanywhere sample search

| gentimes start=-1 | eval myField="535276" |  rex field=myField mode=sed "s/(.)(.)/\2\1/g"
Highlighted

Re: How do I reverse/swap characters in a string value returned from a search?

Explorer

yes the g worked thanks again.