jq add capturing group result outside

拈花ヽ惹草 提交于 2019-12-24 07:03:48

问题


For example,

Input:

    {
       "id":"abc",
       "name": "name-middlenane-lastname-1"
    },

    {
        "id":"123",
        "name": "fname-flast-2"
    }

response:

    {
         "id":"abc",
         "name": "name-middlename-lastname-1",
         "newkey": "name-middlename-lastname"
    },

    {
          "id":"123",
          "name": "fname-flast-2",
          "newkey": "fname-flast"
    }

The filed name in each object is a string with characters and numbers separated by "-" hyphen. I need the complete string from beginning till the starting number. I don't want anything which is there after the number. And then the add new field with key as newkey and value should be extracted string without the number. Thus, the output should contain old fields as well as new one.


回答1:


jq solution:

Sample input.json:

[
  {
    "id": "abc",
    "name": "name-middlenane-lastname-1"
  },
  {
    "id": "123",
    "name": "fname-flast-2"
  }
]

jq 'map(. + (.name | capture("(?<newkey>.+)-[0-9]+")) )' input.json

The output:

[
  {
    "id": "abc",
    "name": "name-middlenane-lastname-1",
    "newkey": "name-middlenane-lastname"
  },
  {
    "id": "123",
    "name": "fname-flast-2",
    "newkey": "fname-flast"
  }
]


来源:https://stackoverflow.com/questions/49553691/jq-add-capturing-group-result-outside

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!