Conversion functions - Splunk Documentation (2024)

The following list contains the functions that you can use to mask IP addresses and convert numbers to strings and strings to numbers.

For information about using string and numeric fields in functions, and nesting functions, see Evaluation functions.

ipmask(<mask>,<ip>)

Description

This function generates a new masked IP address by applying a mask to an IP address through a bitwise AND operation. You can use this function to simplify the isolation of an IPv4 address octet without splitting the IP address.

Usage

The <mask> must be a valid IPv4 address. The <IP> must be a valid IPv4 address or a field name where the field value is a valid IPv4 address.

A valid IPv4 address is a quad-dotted notation of four decimal integers, each ranging from 0 to 255.

For the <mask> argument, you can specify one of the default subnet masks such as 255.255.255.0.

You can use this function with the eval command, and as part of eval expressions.

Basic examples

The following example shows how to use the ipmask function with the eval command:

... | eval maskedIP = ipmask("255.255.255.0", "10.20.30.120")

The output of this example is 10.20.30.0.


The following example shows how to use the ipmask function in the SELECT clause of the from command:

... | eval maskedIP = ipmask("0.255.0.244", clientip) AS maskedip

This search masks every IP address in the clientip field and returns the results in an aliased field called maskedip.


The following example shows how to use the ipmask function in the WHERE clause of the from command to filter the events on a specific mask value:

...| where ipmask("0.255.0.224", clientip)="10.20.30.120"

In this example, the masked value is 0.20.0.96.

printf(<format>,<arguments>)

Description

This function builds a string value, based on a string format and the values specified. You can specify zero or more values. The values can be strings, numbers, computations, or fields.

The SPL printf function is similar to the C sprintf() function and similar functions in other languages such as Python, Perl, and Ruby.

Usage

You can use this function with the eval, fieldformat, and where commands, and as part of eval expressions.

format
Description: The format is a character string that can include one or more format conversion specifiers. Each conversion specifier can include optional components such as flag characters, width specifications, and precision specifications. The format must be enclosed in quotation marks.
Syntax: "(%[flags][width][.precision]<conversion_specifier>)..."
arguments
Description: The arguments are optional and can include the width, precision, and the value to format. The value can be a string, number, or field name.
Syntax: [width][.precision][value]

Supported conversion specifiers

The following table describes the supported conversion specifiers.

Conversion specifierAliasDescriptionExamples
%a or%AFloating point number in hexadecimal formatThis example returns the value of pi to 3 decimal points, in hexadecimal format.

printf("%.3A",pi()) which returns 0X1.922P+1

%cSingle Unicode code pointThis example returns the unicode code point for 65 and the first letter of the string "Foo".

printf("%c,%c",65,"Foo") which returns A,F

%d%iSigned decimal integerThis example returns the positive or negative integer values, including any signs specified with those values.

printf("%d,%i,%d",-2,+4,30) which returns -2,4,30

%e or%EFloating point number, exponential formatThis example returns the number 5139 in exponential format with 2 decimal points.

printf("%.2e",5139) which returns 5.14e+03

%f or%FFloating point numberThis example returns the value of pi to 2 decimal points.

printf("%.2f",pi()) which returns 3.14

%g or%GFloating point number. This specifier uses either%e or%f depending on the range of the numbers being formatted.This example returns the value of pi to 2 decimal points (using the%f specifier) and the number 123 in exponential format with 2 decimal points (using%e specifier).

printf("%.2g,%.2g",pi(),123) which returns 3.1,1.2e+02

%oUnsigned octal numberThis example returns the base-8 number for 255.

printf("%o",255) which returns 377

%s%zStringThis example returns the concatenated string values of "foo" and "bar".

printf("%s%z", "foo", "bar") which returns foobar

%uUnsigned, or non-negative, decimal integerThis example returns the integer value of the number in the argument. printf("%u",99) which returns 99
%x or%X%pUnsigned hexadecimal number (lowercase or uppercase)This example returns the hexadecimal values that are equivalent to the numbers in the arguments. This example shows both upper and lowercase results when using this specifier.

printf("%x,%X,%p",10,10,10) which returns a,A,A

%%Percent signThis example returns the string value with a percent sign.

printf("100%%") which returns 100%

Flag characters

The following table describes the supported flag characters.

Flag charactersDescriptionExamples
single quote or apostrophe ( ' )Adds commas as the thousands separator.printf("%'d",12345) which returns 12,345
dash or minus ( - )Left justify. If this flag is not specified, the result keeps its default justification.
The printf function supports right justification of results only when it formats that way by default.
printf("%-4d",1) which returns 1

which is left justified in the output.

zero ( 0)Zero padThis example returns the value in the argument with leading zeros such that the number has 4 digits.

printf("%04d",1) which returns 0001

plus ( + )Always include the sign ( + or - ). If this flag is not specified, the conversion displays a sign only for negative values.printf("%+4d",1) which returns +1
<space>Reserve space for the sign. If the first character of a signed conversion is not a sign or if a signed conversion results in no characters, a <space> is added as a prefixed to the result. If both the <space> and + flags are specified, the <space> flag is ignored.printf("% -4d",1) which returns 1
hash, number, or pound ( # )Use an alternate form. For the%o conversion specifier, the # flag increases the precision to force the first digit of the result to be zero. For%x or%X conversion specifiers, a non-zero result has 0x (or 0X) prefixed to it. For%a,%A,%e,%E,%f,%F,%%g , and G conversion specifiers, the result always contains a radix character, even if no digits follow the radix character. Without this flag, a radix character appears in the result of these conversions only if a digit follows it. For%g and%G conversion specifiers, trailing zeros are not removed from the result as they normally are. For other conversion specifiers, the behavior is undefined.printf("%#x", 1) which returns 0x1

Specifying field width

You can use an asterisk ( * ) with the printf function to return the field width or precision from an argument.

Examples
The following example returns the positive or negative integer values, including any signs specified with those values.

printf("%*d", 5, 123) which returns 123

The following example returns the floating point number with 1 decimal point.

printf("%.*f", 1, 1.23) which returns 1.2

The following example returns the value of pi() in exponential format with 2 decimal points.

printf("%*.*e", 9, 2, pi()) which returns 3.14e+00


The field width can be expressed using a number or an argument denoted with an asterisk ( * ) character.

Field width specifierDescriptionExamples
numberThe minimum number of characters to print. If the value to print is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.
* (asterisk)The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

Specifying precision

PrecisionDescription
%d,%i,%o,%u,%x or%XPrecision specifies the minimum number of digits to be return. If the value to be return is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is returned for the value 0.
%a or%A,%e or%E,%f or%FThis is the number of digits to be returned after the decimal point. The default is 6 .
%g or%GThis is the maximum number of significant digits to be returned.
%sThis is the maximum number of characters to be returned. By default all characters are printed until the ending null character is encountered.
Specifying the period without a precision valueIf the period is specified without an explicit value for precision, 0 is assumed.
Specifying an asterisk for the precision value, for example .*The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

Unsupported conversion specifiers

There are a few conversion specifiers from the C sprintf() function that are not supported, including:

  • %C, however%c is supported
  • %n
  • %S, however%s is supported
  • %<num>$ specifier for picking which argument to use

Basic examples

This example creates a new field called new_field and creates string values based on the values in field_one and field_two. The values are formatted with 4 digits before the decimal and 4 digits after the decimal. The - specifies to left justify the string values. The 30 specifies the width of the field.

...| eval new_field=printf("%04.4f%-30s",field_one,field_two)

tonumber(<str>,<base>)

Description

This function converts the input string to a number. The string can be a field name or a value.

Usage

You can use this function with the eval, fieldformat, and where commands, and as part of eval expressions.

The <base> is optional and used to define the base of the number in <str>. The <base> can be 2 to 36. The default is 10 to correspond to the decimal system.

If the tonumber function cannot parse a field value to a number, for example if the value contains a leading and trailing space, the function returns NULL.Use the trim function to remove leading or trailing spaces.

If the tonumber function cannot parse a literal string to a number, it returns an error.

Binary conversion

You can use this function to convert a string representation of a binary number to return the corresponding number in base 10. For example, the result of the following function is 5:

eval result = tonumber("0101", 2)

This is because the decimal representation of 0101 is 5.

For information about bitwise functions that you can use with the tonumber function, see Bitwise functions.

Basic examples

The following example converts the string values for the store_sales field to numbers.

... | eval n=tonumber(store_sales)


The following example takes the hexadecimal number and uses a <base> of 16 to return the number "164".

... | eval n=tonumber("0A4",16)


The following example trims any leading or trailing spaces from the values in the celsius field before converting it to a number.

... | eval temperature=tonumber(trim(celsius))

tostring(<value>,<format>)

Description

This function converts a value to a string. If the value is a number, this function reformats it as a string. If the value is a Boolean value, it returns the corresponding string value, "True" or "False".

Usage

You can use this function with the eval, fieldformat, and where commands, and as part of eval expressions.

This function requires at least one argument, the value.

Only integers in the range of 0 to 253 -1 are accepted as input to the function. For example, tostring("5", "binary") is not supported.

When used with the eval command, the values might not sort as expected because the values are converted to ASCII. Use the fieldformat command with the tostring function to format the displayed values. The underlying values are not changed with the fieldformat command.

If <value> is a number, the <format> is optional. Supported formats are "binary", "hex", "commas", or "duration".

ExamplesDescription
tostring(X,"binary")Converts X to binary.
tostring(<value>,"hex")Converts the value to hexadecimal.
tostring(<value>,"commas")Formats the value with commas. If the number includes decimals, the function rounds to nearest two decimal places.
tostring(<value>,"duration")Converts a value in seconds to the readable time format HH:MM:SS.

Binary conversion

You can use this function to convert a number to a string of its binary representation. For example, the result of the following function is 1001:

eval result = tostring(9, "binary")

This is because the binary representation of 9 is 1001.

For information about bitwise functions that you can use with the tostring function, see Bitwise functions.

Basic examples

The following example returns "True 0xF 12,345.68".

... | eval n=tostring(1==1) + " " + tostring(15, "hex") + " " + tostring(12345.6789, "commas")

The following example returns foo=615 and foo2=00:10:15. The 615 seconds is converted into minutes and seconds.

... | eval foo=615 | eval foo2 = tostring(foo, "duration")

The following example formats the column totalSales to display values with a currency symbol and commas. You must use a period between the currency value and the tostring function.

... | fieldformat totalSales="$".tostring(totalSales,"commas")

See also

Commands
convert
Functions
strptime
Conversion functions - Splunk Documentation (2024)

FAQs

What is the convert function in Splunk? ›

The convert command in Splunk uses a wide array of conversion functions to manipulate fields in Splunk. These conversions involve operations like changing strings to numeric values, changing time format, and improving the usability or readability of numeric fields with specific units.

What is the difference between Strftime and Strptime in Splunk? ›

Strftime stands for “String from time” and uses a UNIX timestamp to create a string showing a human-readable timestamp. Strptime stands for “String parsed time” and turns a human-readable timestamp into a UNIX timestamp. Together, these two functions unlock many use cases for our data.

What is _time in Splunk? ›

When an event is processed by Splunk software, its timestamp is saved as the default field _time . This timestamp, which is the time when the event occurred, is saved in UNIX time notation.

How to get yesterday's date in Splunk? ›

You could either do a simple string match where clause on the PUBLISHED_DATETIME field or comvert it to epoch and compare. So, you need to format a string like eval yesterday=... and then the where clause will string match.

What is conversion functions explain? ›

Conversion functions convert a value from one datatype to another. Generally, the form of the function names follows the convention datatype. TO datatype. The first datatype is the input datatype.

What is To_char To_number and To_date conversion functions? ›

Ø It converts a char, value of CHAR or varchar2 data type containing a number in the format specified by the optional format model 'fmt' to a value of number data type. Ø Converts given char of CHAR or VARCHAR2 data type to a value of DATE data type. Ø The 'fmt' is an optional date format specifying the format of char.

How do you convert duration to minutes in Splunk? ›

Duration is in seconds so divide by 60 to get minutes. Duration is in seconds so divide by 60 to get minutes.

What is the difference between datetime and Timedelta? ›

While datetime objects represent specific points in time (e.g., January 1st, 2024 at 10:30 AM), timedelta objects represent durations or intervals between two points.

What is the difference between time and timestamp in Splunk? ›

Timestamps are stored in UNIX time

Regardless of how time is specified in your events, timestamps are converted to UNIX time and stored in the _time field when your data is indexed. If your data does not have timestamps, the time at which your data is indexed is used as the timestamp for your events.

What is the difference between bin and timechart in Splunk? ›

timechart will fill in the gaps in the timeline - for example, if your time range (earliest to latest) was 09:00 to 09:15, - timechart would give you events for 09:00, 09:05 and 09:10, regardless of whether there was an event, whereas bin would only give you (aggregated) events for these times if there was an event in ...

How big is the Splunk persistent queue? ›

persistent queue

By default, forwarders and indexers have an in-memory input queue of 500 KB.

What is the difference between Splunk _time and _indextime? ›

_time is the timestamp of the actual event; whereas, _indextime is the timestamp when Splunk actually indexed the event. Depending on the input, these two timestamps may be very far apart. For example, if you use a file monitor input that has data from a year ago, _time will be a year ago, but _indextime will be "now".

How do I search between two dates in splunk? ›

To search for data using an exact date range, such as from October 15 at 8 PM to October 22 at 8 PM, use the timeformat %m/%d/%Y:%H:%M:%S and specify dates like earliest="10/15/2019:20:00:00" latest="10/22/2019:20:00:00" To search for data from the beginning of today (12 AM or midnight) use earliest=@d .

What format does splunk use for time? ›

The values are stored in UNIX format and converted using the format specified, which is the ISO 8601 format. For example: 2022-04-13T14:00:15.000.

How do I see previous queries in splunk? ›

Your full search history appears at the bottom of the Search Summary view. Use the Search History panel to view and interact with the searches that you have previously run. Click the greater than ( > ) symbol to expand the display to view your search history.

What does convert () do? ›

Converts a number from one measurement system to another. For example, CONVERT can translate a table of distances in miles to a table of distances in kilometers.

What does a convert do? ›

A convert is someone who has changed their religious or political beliefs. She, too, was a convert to Roman Catholicism.

What does convert command mean? ›

The convert command is used to change FAT volumes to NTFS.

What is the difference between convert and Try_convert? ›

SQL Server TRY_CONVERT() function converts an expression of one type to the specified type. It returns NULL if cannot convert it. The TRY_CONVERT() and the CONVERT() functions are similar except when the conversion is unsuccessful TRY_CONVERT() returns a NULL and CONVERT() throws an error.

References

Top Articles
Latest Posts
Article information

Author: Golda Nolan II

Last Updated:

Views: 5795

Rating: 4.8 / 5 (58 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Golda Nolan II

Birthday: 1998-05-14

Address: Suite 369 9754 Roberts Pines, West Benitaburgh, NM 69180-7958

Phone: +522993866487

Job: Sales Executive

Hobby: Worldbuilding, Shopping, Quilting, Cooking, Homebrewing, Leather crafting, Pet

Introduction: My name is Golda Nolan II, I am a thoughtful, clever, cute, jolly, brave, powerful, splendid person who loves writing and wants to share my knowledge and understanding with you.