Splunk Search

How to create a conditional rex statement on file extension or directory?

mjones414
Contributor

I'm trying to figure out how to do a conditional rex statement that looks at a windows file path and determines if the last segment of the path has a ., it creates a field called extension, but if it doesn't end with an extension, it creates a field called directory and puts the full value (with spaces) of the last directory in the segment. Is there a way to do a conditional statement like this with rex?

Tags (2)
0 Karma

cpetterborg
SplunkTrust
SplunkTrust

Given your question and the data that you have provided, I think that this "run anywhere" search shows a rex that will work as you have requested:

| makeresults | eval data="c:\test directory with spaces\test_directory_with_underscores\filename (with: horrible habits).txt|c:\test directory with spaces\test_directory_with_underscores\little-child-directory" 
| makemv delim="|" data
| mvexpand data 
| rex field=data "(\.(?<ext>[^.]+)|\\\(?<dir>[^.\\\]+))$"

This rex requires some additional backslashes to make it interpret the backslashes that might appear on the file path, but it clearly shows that you can get one or the other of the fields that you want to extract from the data. The first three lines are just setting up the data, and the last one (with the rex command) is the one with all the magic.

0 Karma

richgalloway
SplunkTrust
SplunkTrust

Please share some sample data and desired extractions.

---
If this reply helps you, Karma would be appreciated.
0 Karma

mjones414
Contributor

Surely 🙂

FieldName=Object

Value Examples:
c:\test directory with spaces\test_directory_with_underscores\filename (with: horrible habits).txt
c:\test directory with spaces\test_directory_with_underscores\little-child-directory

Simple rex to get file extension:

| rex field="object" "\.(?<extension>[^\.]*$)"

extension:
txt

(if extension is null, delimit by the last backslash .*$ and create a field called Directory with the value)

Directory:
(want this to be little-child-directory)

0 Karma
Get Updates on the Splunk Community!

Splunk + ThousandEyes: Correlate frontend, app, and network data to troubleshoot ...

 Are you tired of troubleshooting delays caused by siloed frontend, application, and network data? We've got a ...

Splunk Observability for AI

Don’t miss out on an exciting Tech Talk on Splunk Observability for AI!Discover how Splunk’s agentic AI ...

🔐 Trust at Every Hop: How mTLS in Splunk Enterprise 10.0 Makes Security Simpler

From Idea to Implementation: Why Splunk Built mTLS into Splunk Enterprise 10.0  mTLS wasn’t just a checkbox ...