Search

Dark theme | Light theme

October 4, 2023

jq Joy: Checking String Ends Or Starts With Given String

jq is a powerful tool to work with JSON from the command-line. The tool has a lot of functions that makes our live easier. We can check if a string starts or ends with a given string using the startswith and endswith functions. We pass the string value we want to see a string value starts with or ends with as the argument to the functions. The function returns true if the string starts or ends with the given string and false otherwise.

In the following examples we use both functions to check some string values in an array:

$ jq --null-input '["mrhaki", "hubert", "MrHaki"] | [.[] | startswith("mr") or startswith("Mr")]'
[
    true,
    false,
    true
]
$ jq --null-input '["jq!", "JSON"] | [.[] | endswith("!")]'
[
  true,
  false
]

Written with jq 1.7.