100% found this document useful (1 vote)
79 views10 pages

Splunk Command Cheat Sheet

This document provides a cheat sheet of common commands for the Splunk software. It summarizes commands for basic searches, filtering, extraction, aggregation, statistics, lookups, enrichment, visualization, reporting, alerting and batch processing of log data in Splunk.

Uploaded by

mahdi aghaei
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
79 views10 pages

Splunk Command Cheat Sheet

This document provides a cheat sheet of common commands for the Splunk software. It summarizes commands for basic searches, filtering, extraction, aggregation, statistics, lookups, enrichment, visualization, reporting, alerting and batch processing of log data in Splunk.

Uploaded by

mahdi aghaei
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

splunk Cheat Sheet

Basic Commands

Command Description Example

search Initiates a search for events based on specified criteria index=web_logs status=200

index Specifies the index to search within index=web_logs


sourcetype Filters events based on the specified sourcetype sourcetype=apache_access

Filtering and Extraction

Command Description Example


where Filters events based on conditions index=logs | where status="error"
Creates new fields or modifies existing index=logs | eval latency_ms=response_time/1000
eval
ones | table latency_ms
Performs regular expression extraction index=logs | rex field=message "Error:
rex
on fields (?<error_message>.*)"
Enhanced regular expression extraction
erex index=logs | erex "Error: (?<error_message>.*)"
with named capture groups

Aggregation and Statistics

Command Description Description


Generates statistics and calculations on index=sales | stats sum(price) as total_sales
stats
fields by product
Creates time-based charts and aggregates
timechart index=web_logs | timechart count by status
data over time
Generates charts and graphs based on index=web_logs | chart avg(response_time)
chart
specified fields by uri
Performs statistics calculations on events index=transactions | eventstats avg(amount)
eventstats
and adds results as new fields as avg_amount by user
Grouping and Transactional Analysis

Command Description Description


Groups related events into index=transactions | transaction user
transaction
transactions based on conditions startswith="login" endswith="logout"
Counts occurrences of unique
stats count by index=web_logs | stats count by status
values in a field
stats earliest, Retrieves the earliest and latest index=logs | stats earliest(_time) as first_event
latest by events for each value in a field latest(_time) as last_event by user

Field Manipulation

Command Description Description


Specifies fields to be included in
fields index=logs | fields timestamp, source, message
the search results
Renames fields in the search
rename index=logs | rename old_field as new_field
results
Applies formatting to field index=metrics | eval formatted_latency =
fieldformat
values in search results fieldformat(response_time, "duration")
Adds row and column totals to index=sales | addcoltotals useother=f sum(price) as
addcoltotals
tabular search results total_price

Data Transformation

Command Description Description


Applies sed-like replacements index=logs | rex mode=sed
rex mode=sed
using regular expressions field=description "s/error/warning/g"
Extracts structured data from fields index=logs | spath input=raw output=uri
spath
containing JSON or XML path=uri
Extracts specific paths from index=logs | spath input=raw output=page
spath output path
structured data as separate fields path=uri
spath input path Extracts structured data with index=logs | spath input=raw output=page
output path default default values if path is not found path=uri default="Unknown"
Lookup and Enrichment
Command Description Description
Enhances data with additional information index=logs | lookup user_info.csv username
lookup
from lookup tables as user
inputlookup Loads lookup data into a search | inputlookup user_info.csv
index=logs | stats count by user |
outputlookup Saves search results into a lookup file
outputlookup user_counts.csv

Advanced Analysis
Command Description Description
index=logs | eval priority = case(severity=="High",
eval case() Performs conditional evaluation "Urgent", severity=="Medium", "Normal", true(),
"Low")
index=logs | eval important_info =
eval Returns the first non-null value
coalesce(critical_message, warning_message,
coalesce() among arguments
info_message)
Rounds a numeric field to a
eval
specified number of decimal index=metrics | eval rounded_value = round(value, 2)
round()
places
eval Joins multivalue fields into a
index=events | eval combined_tags = mvjoin(tags, ", ")
mvjoin() single value using a separator
Converts a Unix timestamp to a
eval index=logs | eval formatted_time = strftime(_time,
human-readable date and time
strftime() "%Y-%m-%d %H:%M:%S")
format

Subsearch and Correlation


Command Description Description
Embeds a subsearch within the main search index=access_logs [ search index=error_logs
subsearch
to correlate events | stats count ]
Accelerated statistics command for | tstats count where index=web_logs by
tstats
summarizing indexed data sourcetype
Visualization and Reporting
Command Description Description
timechart Creates time-based charts with specified index=web_logs | timechart span=1h
span time spans sum(response_time)
Generates geospatial statistics and
geostats index=locations | geostats count by city
visualizations
Includes NULL values in chart
chart usenull index=logs | chart count by user usenull=f
visualizations
index=sales | rangemap price
rangemap Maps field values to ranges for reporting
output_field=price_range
Generates XY chart visualizations from
xyseries index=metrics | xyseries x=time y=values
multivalue fields

Alerting and Monitoring


Command Description Description
Sets up alerts based on specified index=errors | stats count as error_count | alert
alert
conditions threshold=100 "High Error Count"
Aggregates and stores events for
collect index=access_logs | collect index=access_history
future analysis
track_alert Tracks alert activity and results index=_audit action="alert_fired" | stats count by alert

Batch Mode and Lookup


Command Description Description
| multisearch [ search index=logs ] [ search
multisearch Runs multiple searches in parallel
index=metrics ]
Searches in parallel with session | multisearch SID=search1 [ search index=logs ]
multisearch SID
ID [ search index=metrics ]
Loads data from a CSV file into
inputcsv | inputcsv [Link]
the search
inputlookup Appends data from a lookup table index=logs | inputlookup append=t
append=t to the search results lookup_table.csv
Working with Time
Command Description Description
Converts a string to a index=logs | eval event_time = strptime(timestamp, "%Y-
strptime
timestamp format %m-%d %H:%M:%S")
earliest Specifies time ranges for the
index=logs earliest=-7d latest=now
latest search
Groups events into time
bucket index=logs | bucket span=1h _time
buckets

String Functions
Command Description Description
Extracts a substring from a field's index=logs | eval short_message =
substr
value substr(message, 1, 50)
index=logs | eval message_length =
len Returns the length of a string field
len(message)
toupper Converts string values to uppercase or index=logs | eval uppercase_message =
tolower lowercase toupper(message)

Math Functions
Command Description Description
Rounds numeric values to the nearest whole index=metrics | eval rounded_value =
round
number round(value)
index=metrics | eval absolute_value =
abs Returns the absolute value of a number
abs(change)
index=metrics | eval square_root =
sqrt Calculates the square root of a number
sqrt(number)
index=metrics | eval squared_value =
power Raises a number to a specified power
power(value, 2)
Computes the natural logarithm or base-10
log log10 index=metrics | eval ln_value = log(value)
logarithm
Conditional Functions

Command Description Description


Returns different values based index=logs | eval status_type = if(status>=400, "Error",
if()
on a condition "Success")
Evaluates a series of conditions index=logs | eval severity_level = case(severity=="High",
case()
and returns values accordingly 3, severity=="Medium", 2, severity=="Low", 1)
Returns the first non-null value
coalesce() ``index=logs \n
among arguments

Logical Functions

Command Description Description


Performs logical AND, OR, and NOT index=logs | eval is_error = (severity=="High" OR
and or not
operations status>=500)
Matches field values with wildcard index=logs | eval is_error = like(message,
eval like
patterns "*error*")
Filters multivalue fields based on index=events | eval tags = mvfilter(tag, like(tag,
mvfilter
conditions "*critical*"))

Working with Multivalue Fields

Command Description Description


Expands multivalue fields into
mvexpand index=events | mvexpand tags
separate events
mvzip mvappend index=events | eval combined_fields =
Manipulates multivalue fields
mvcombine mvzip(field1, field2, ", ")
Counts the number of values in a index=events | eval tag_count =
mvcount
multivalue field mvcount(tags)
Searches for values in a index=events | eval has_error = mvfind(tags,
mvfind
multivalue field "error")
Numeric Functions

Command Description Description


isnull index=metrics | eval missing_value =
Checks if a field value is null or not null
isnotnull isnull(response_time)
index=metrics | eval is_number =
isnum Checks if a field value is a number
isnum(value)
isbool Checks if a field value is a boolean index=events | eval is_boolean = isbool(flag)
Joins multivalue fields into a single value index=events | eval combined_tags =
mvjoin
using a separator mvjoin(tags, ", ")

Time and Date Functions

Command Description Description


now Returns the current date and time index=logs | eval current_time = now()
Converts between Unix timestamps index=logs | eval formatted_time =
strptime strftime
and human-readable dates strftime(_time, "%Y-%m-%d %H:%M:%S")
Calculates a relative time based on index=logs earliest=relative_time(now(), "-
relative_time
a unit and offset 1d@d")
date_month Extracts month or day of the week
index=logs | eval month = date_month(_time)
date_wday from timestamps
Returns the current time with an
now offset index=logs | eval future_time = now() + 3600
offset
Converts a string representation of index=logs | eval event_time = time("2023-01-
time
time to a Unix timestamp 15 10:30:00")
Extracts specific components (year, index=logs | eval year = date_part(_time,
date_part
month, day, etc.) from a timestamp "year")
IP and Geolocation Functions
Command Description Description
Retrieves geolocation information
iplocation index=logs | iplocation clientip
for IP addresses
Matches IP addresses against CIDR index=network_traffic | cidrmatch(ip,
cidrmatch
ranges "[Link]/24")
Checks if a field value is an IPv4 or index=logs | eval is_ipv4 =
isipv4 isipv6
IPv6 address isipv4(ip_address)
Retrieves geolocation information index=logs | maxmindisplocation
maxmindisplocation
from MaxMind databases ipfield=client_ip
Maps IP addresses to domain index=network_traffic | eval hostname =
iptoname
names iptoname(destination_ip)

Geospatial Functions
Command Description Description
Generates geospatial statistics and
geostats index=locations | geostats count by city
visualizations
Calculates the distance between two index=locations | eval distance_km =
geodistance
sets of geographic coordinates geodistance(lat1, lon1, lat2, lon2, "km")
Calculates the bounding box of a set index=locations | geobounds latfield=latitude
geobounds
of geographic coordinates lonfield=longitude
Converts latitude and longitude to a index=locations | eval geopoint =
geopoint
geopoint field geopoint(latitude, longitude)
geom Calculates the distance between two index=locations | eval distance_km =
distance geopoint fields geom_distance(geopoint1, geopoint2, "km")

Advanced Transformations
Command Description Description
Extracts structured data from index=logs | spath input=raw output=uri
spath
fields containing JSON or XML path=uri
Extracts specific paths from index=logs | spath input=raw output=page
spath output path
structured data as separate fields path=uri
Command Description Description
Extracts structured data with index=logs | spath input=raw output=page
spath output default
default values if path is not found path=uri default="Unknown"
index=logs | spath input=raw
spath input path Extracts structured data with
output=status_code path=code
output path default specific paths and default values
default="N/A"

Conditional Transformations

Command Description Description


Performs conditional
index=logs | eval priority = case(severity=="High",
case() evaluations and returns
"Urgent", severity=="Medium", "Normal", true(), "Low")
values
Returns different values index=logs | eval alert_level = if(severity=="High",
if()
based on a condition "Critical", "Normal")
eval Returns the first non-null index=logs | eval important_info =
coalesce() value among arguments coalesce(critical_message, warning_message, info_message)

Timechart and Chart Functions

Command Description Description


timechart Creates time-based charts with specified index=web_logs | timechart span=1h
span time spans sum(response_time)
Includes NULL values in chart
chart usenull index=logs | chart count by user usenull=f
visualizations
index=web_logs | chart count over status by
chart overlay Generates overlay charts based on fields
host
Creates span charts with time and non-
chart span index=events | chart count by user span=1d
time fields
chart stack Generates stacked charts based on fields index=web_logs | chart count stack by status
Creates histogram-style charts with
chart bins index=metrics | chart count bins=10 by value
specified bin sizes
Advanced Analysis and Correlation

Command Description Description


stats first Retrieves the first and last values of index=events | stats first(_time) as first_event
last fields last(_time) as last_event by user
Performs statistics calculations on events index=transactions | eventstats avg(amount) as
eventstats
and adds results as new fields avg_amount by user
rare Identifies rare values in a field index=errors | rare error_code
Removes duplicate events based on
dedup index=logs | dedup user, ip_address
specified fields
multikv Extracts key-value pairs from fields index=logs | multikv fields key1, key2

You might also like