105

input json:

[
  {
    "id": "89",
    "hostname": "abcd"
  },
  {
    "id": "89",
    "hostname": "babcd"
  }
]

How to modify below filter to get on output only hostname beginning with "abcd"?

$ jq -r '.[]|select(.hostname | contains("abcd"))' jjjj
{
  "id": "89",
  "hostname": "abcd"
}
{
  "id": "89",
  "hostname": "babcd"
}
$ jq -r '.[]|select(.hostname | contains("^abcd"))' jjjj
$
0

1 Answer 1

157

Solution:

jq -r '.[]|select(.hostname | startswith("abcd"))' jjjj
3
  • 9
    For anyone wondering, you can also use endswith() if that's what you want to check
    – lxop
    Jul 29, 2020 at 22:25
  • 4
    And if you need the output to be an array, then you should use map. Example: jq 'map( select(.hostname | startswith("abcd") ) )'. Then you can select the first match by simply using | first
    – ST-DDT
    Oct 7, 2021 at 10:03
  • 4
    And since we're on the topic -- you can also use contains("xyz"), if that's your cup of tee. :D
    – tftd
    May 31, 2023 at 10:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .