How To Get Substring In Splunk?

A substring about Splunk is a portion of a text or string which can be extracted from a huge string using certain search commands. To define a substring, you need to start and end a position within the bigger string.

Extracting substring in Splunk?

There are numerous methods of extracting a substring in Splunk. These include using the search commands below:

  1. regex: It’s utilized in extracting a certain pattern or group of characters from a string with the help of regular expressions.
  2. substr: It’s used in extracting some number of characters from the string, beginning at a certain position.
  3. extract: It’s utilized in extracting certain values or fields from a string with the help of a defined pattern or delimiter.

Examples of using substring in Splunk

  1. Using regex: Extracts the domain name from the email address. One can utilize this search command: | rex field=email “(?<domain>[a-z]+\.com)”
  2. Using substr: Extracts the first 10 characters of a string. One can utilize this search command: | eval new_field=substr(original_field,0,10)
  3. Using extract: Extracts the value of a certain field from JSON string with this search command: | extract pairdelim=”}” kvdelim=”:” json=json_field

Using “substr” function

substr function enables one to extract certain string portions. The syntax for this function is:

  • substr(string, start, length)
  • string: string where you need to extract a substring
  • start: the substring starting position (0-based index)
  • length: It’s the number of characters one needs to extract

Example:

| eval substring=substr(string, 5, 10)

The above function will extract a substring of 10 characters beginning at position 5 of the “string” field.

Using the “rex” command

The rex function enables one to extract a substring with the help of a regular expression. The command syntax is as the following:

rex field=string “(?<substring>pattern)”

field: refers to the field from where you need to extract a substring

string: regular expression pattern which defines substring

Example:

| rex field=string “(?<substring>\d{3}-\d{2}-\d{4})”

This extracts a substring that matches the social security number pattern (xxx-xx-xxxx) from the “string” field.

Using the “eval” command

This enables one to form a new field plus assign it a value depending on an expression. Its syntax is:

eval new_field=expression

new_field: It’s the new field’s name which contains the substring

expression: the expression which defines substring

Example:

| eval substring=substr(string, 5, 10)

This creates a new field known as “substring” & assigns it a value that’s a substring of the “string” field beginning at position 5 & with 10 characters.

Leave a Comment