104

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
$
Jagger
  • 153
Chris
  • 4,091

1 Answers1

155

Solution:

jq -r '.[]|select(.hostname | startswith("abcd"))' jjjj
Chris
  • 4,091
  • 9
    For anyone wondering, you can also use endswith() if that's what you want to check – lxop Jul 29 '20 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 07 '21 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 '23 at 10:01