【问题标题】:How to use regex to search the key and value and replace value with new value using jq如何使用正则表达式搜索键和值并使用 jq 将值替换为新值
【发布时间】:2019-05-23 11:22:17
【问题描述】:
My json
{
    "license": " See license.md",
    "dependencies": {
        "@gx/core": "0.279.0-b1-abc-1234-0716.4567",
        "@gx/api": "0.279.0-b1-abc-1234-0716.4567",
        "@gx/name": "0.279.0-b1-abc-1234-0716.4567"
    }
}

我想在所有地方将“0.279.0-b1-abc-1234-0716.4567”替换为“0.279.0-b1-abc-1234-0716.9856”。

        jq '.dependencies[].["@gx/core"] |= (if . == "0.279.0-b1-abc-1234-0716.4567" then "0.279.0-b1-abc-1234-0716.9856" else . end)' info.json
jq: error: syntax error, unexpected '[', expecting FORMAT or QQSTRING_START (Unix shell quoting issues?) at <top-level>, line 1:
    .dependencies[].["@gx/core"] |= (if . == "0.279.0-b1-abc-1234-0716.4567" then "0.279.0-b1-abc-1234-0716.9856" else . end)                
    jq: 1 compile error   

I am looking for something like this
   jq '.dependencies[].["@gx/[a-z]*"] |= (if . == "^(\d+\.){2}[0-9]+(-[a-zA-Z0-9]*){4}\.[0-9]*$" then "0.279.0-b1-abc-1234-0716.9856" else . end)' info.json 

【问题讨论】:

    标签: json regex key jq


    【解决方案1】:

    使用 jq,有许多不同的方法,具有非常不同的语义,从第一个问题的这些解决方案中可以看出(没有正则表达式):

    walk(if . == "0.279.0-b1-abc-1234-0716.4567" 
         then "0.279.0-b1-abc-1234-0716.9856" else . end)
    

    更专注的方法:

     .dependencies |=
       map_values(if . == "0.279.0-b1-abc-1234-0716.4567" 
                  then "0.279.0-b1-abc-1234-0716.9856" else . end)
    

    正则表达式

    上述方法也都可以用于正则表达式搜索,例如最后一种情况会变成:

    .dependencies |= with_entries(
      if (.key | test("@gx/[a-z]*"))
          and (.value | test("^(\\d+\\.){2}[0-9]+(-[a-zA-Z0-9]*){4}\\.[0-9]*$"))
      then .value = "0.279.0-b1-abc-1234-0716.9856" else . end)
    

    请注意,正则表达式字符串必须是 JSON 字符串,因此反斜杠加倍。

    if 没有 else

    如果你有足够新的 jq 版本,那些悬空出现的“else”。可以丢弃。

    【讨论】:

    【解决方案2】:

    如果您考虑使用非 jq 解决方案,让我在这里提供一个基于步行路径 unix 实用程序的解决方案 jtc

    bash $ <file.json jtc -w'[dependencies]<0\.279\.0\-b1\-abc\-1234\-0716\.4567>R:' -u'"0.279.0-b1-abc-1234-0716.9856"'
    {
       "dependencies": {
          "@gx/api": "0.279.0-b1-abc-1234-0716.9856",
          "@gx/core": "0.279.0-b1-abc-1234-0716.9856",
          "@gx/name": "0.279.0-b1-abc-1234-0716.9856"
       },
       "license": " See license.md"
    }
    bash $ 
    

    步行路径 (-w):

    • [dependencies] 地址(从根)给定记录
    • &lt;...&gt;R: - 搜索词位,使用 RE(后缀 R)查找与给定 reg.expression 匹配的所有(量词 :)条目。

    -u 将更新(替换)所有找到的匹配项。

    -- 或--

    使用你的 RE,匹配标签和值:

    bash $ <file.json jtc -w'[dependencies]<@gx/[a-z]*>L:<^(\d+\.){2}[0-9]+(-[a-zA-Z0-9]*){4}\.[0-9]*$>R' -u'"0.279.0-b1-abc-1234-0716.9856"'
    
    • 结果相同

    PS> 披露:我是jtc 工具的创建者

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-02
      • 2016-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-23
      • 2017-02-16
      相关资源
      最近更新 更多