Splunk Search

How to extract the date from the file name without modifying datetime.xml?

Kavey
Path Finder

Hi everyone,

I am currently trying to extract the date from the filename so I can use it for all events include in that file. After some research, I found out that it is possible to do it with the file datetime.xml, like it has been said in those 2 topics :
- http://blogs.splunk.com/2009/12/02/configure-splunk-to-pull-a-date-out-of-a-non-standard-filename/
- https://answers.splunk.com/answers/7800/how-to-override-date-use-filename-instead-of-extracted-value...

However, I would like to know if there was an easier way to do it without touching this file?

Thank you in advance for your help!

javiergn
Super Champion

You could do it at search time by using the source field.

For instance, if you are reading from the following file: "/var/log/myfile_20160415.log", then:

your search here
| rex field=source "/[^/]+(?<date>\d{8})[^/]+$"

Will give you:

date = 20160415

Not sure if that helps so please let me know.

0 Karma

Kavey
Path Finder

Thank you for your help, I think that could do the trick but is it possible to extract with a specific format directly (like 2016-04) without using eval so I can order it by date?

0 Karma

javiergn
Super Champion

I'm not 100% what you are trying to achieve.
You could extract year, month and day in separate variables but then you would need eval to join them in a another variable. You could use this final variable to order by date if you wanted to.

Or you could create an epoch time from your date variable and then use it in the same way and order your events by that field.

In summary, option A:

your search here
| rex field=source "/[^/]+(?<year>\d{4})(?<month>\d{2})(?<day>\d{2})[^/]+$"
| eval date = year + "-" + month + "-" + day
| sort limit=0 date

Option B:

your search here
| rex field=source "/[^/]+(?<date>\d{8})[^/]+$"
| eval date_epoch = strptime(date, "%Y%m%d")
| sort limit=0 date_epoch
0 Karma
Get Updates on the Splunk Community!

[Puzzles] Solve, Learn, Repeat: Dynamic formatting from XML events

This challenge was first posted on Slack #puzzles channelFor a previous puzzle, I needed a set of fixed-length ...

Enter the Agentic Era with Splunk AI Assistant for SPL 1.4

  &#x1f680; Your data just got a serious AI upgrade — are you ready? Say hello to the Agentic Era with the ...

Stronger Security with Federated Search for S3, GCP SQL & Australian Threat ...

Splunk Lantern is a Splunk customer success center that provides advice from Splunk experts on valuable data ...