skip to Main Content

I have following data.json to be modified , I want to change the state to "disabled" based on the filtered IP address range(eg "10.13*". I tried following command and I need to get whole json content as the out put, but i’m getting a syntax errors for this(I have used same for updating a single value(without using character mapping), it worked fine. (Plan is to use this in shell command and redirect the out put to a new file). Can someone help me on this

jq '(.[]| select(.node|test("^10.13*"))).state |="disabled" data.json
[
    {
        "node":"10.13.248.254:61052",
        "state": "active"
    },
    {
        "node":"10.13.248.255:61052",
        "state": "active"
    },
    {
        "node":"10.54.247.228:61052",
        "state": "active"
    },
    {
        "node":"10.54.247.229:61052",
        "state": "active"
    }
]

2

Answers


  1. Your regex isn’t quite right. Also, it might be worthwhile using map to make things more straightforward:

    map(if (.node|test("^10[.]13[.].*")) then .state="disabled" else . end)
    

    Or you could simply use startswith.

    Login or Signup to reply.
  2. If you only want to modify array elements whose IP address starts with "10.13.", you’d usually use map and combine with startswith (for prefix-matching the IP address):

    jq 'map(select(.node|startswith("10.13.")).state = "disabled")' input.json
    

    An equivalent solution assigning multiple values at once:

    jq '(.[]|select(.node|startswith("10.13")).state) = "disabled"' input.json
    

    Note that the second solution is almost identical to your proposed one (with slight modifications: different grouping, startswith, and the plain assignment operator)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search