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!

Introducing the 2024 SplunkTrust!

Hello, Splunk Community! We are beyond thrilled to announce our newest group of SplunkTrust members!  The ...

Introducing the 2024 Splunk MVPs!

We are excited to announce the 2024 cohort of the Splunk MVP program. Splunk MVPs are passionate members of ...

Splunk Custom Visualizations App End of Life

The Splunk Custom Visualizations apps End of Life for SimpleXML will reach end of support on Dec 21, 2024, ...