85

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
  • 1
  • 6
Chris
  • 3,591
  • 7
  • 24
  • 35

1 Answers1

129

Solution:

jq -r '.[]|select(.hostname | startswith("abcd"))' jjjj
Chris
  • 3,591
  • 7
  • 24
  • 35
  • 8
    For anyone wondering, you can also use `endswith()` if that's what you want to check – lxop Jul 29 '20 at 22:25
  • 3
    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
  • 1
    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