Splunk Search

How to extract string before specific character

marinella26
Explorer

Hello. I want to extract strings anything comes before "|" .

ex.
Math |
Math | Science | Math
English | Math
Science | Science | Science | Science

Expected result:
Math
Math
English
Science

Below search did not worked.

my search | stats count by Subject="(?<Subject>[^\|]+)"

Please help me out.

 

Labels (7)
0 Karma
1 Solution

gcusello
SplunkTrust
SplunkTrust

Hi @marinella26 ,

you can use:

| rex "^(?<field>[^\|]+)"

that you can test at https://regex101.com/r/6Ynayk/1

Ciao.

Giuseppe

View solution in original post

gcusello
SplunkTrust
SplunkTrust

Hi @marinella26 ,

you can use:

| rex "^(?<field>[^\|]+)"

that you can test at https://regex101.com/r/6Ynayk/1

Ciao.

Giuseppe

yuanliu
SplunkTrust
SplunkTrust

Read rex.  stats command doesn't have a function to do extraction.

Meanwhile, your sample code suggests that Splunk gives you a field named Subject and you are trying to get some info from this field.  If this is the case, there is a slightly more efficient way using split function:

my search
| Subject = mvindex(split(Subject, "|"), 0)
| stats count by Subject

Another way equivalent to rex is to use replace function.

Get Updates on the Splunk Community!

Splunk Observability Cloud’s AI Assistant in Action Series: Analyzing and ...

This is the second post in our Splunk Observability Cloud’s AI Assistant in Action series, in which we look at ...

Elevate Your Organization with Splunk’s Next Platform Evolution

 Thursday, July 10, 2025  |  11AM PDT / 2PM EDT Whether you're managing complex deployments or looking to ...

Splunk Answers Content Calendar, June Edition

Get ready for this week’s post dedicated to Splunk Dashboards! We're celebrating the power of community by ...