shell 如何使用sed命令替换json文件中的值

kr98yfug  于 2022-11-16  发布在  Shell
关注(0)|答案(2)|浏览(323)

我的json文件看起来像这样:

"parameters": {
    "$connections": {
        "value": {
            "azureblob": {
                "connectionId": "/subscriptions/2b06d50xxxxxedd021/resourceGroups/Reource1005/providers/Microsoft.Web/connections/azureblob",
                "connectionName": "azureblob",
                "connectionProperties": {
                    "authentication": {
                        "type": "ManagedServiceIdentity"
                    }
                },
                "id": "/subscriptions/2b06d502-3axxxxxxedd021/providers/Microsoft.Web/locations/eastasia/managedApis/azureblob"
            },
            "office365": {
                "connectionId": "/subscriptions/2b06d502xxxxxc8-5a8939edd021/resourceGroups/Reource1005/providers/Microsoft.Web/connections/office365",
                "connectionName": "office365",
                "id": "/subscriptions/2b06d50xxxxxx939edd021/providers/Microsoft.Web/locations/eastasia/managedApis/office365"
            }
        }
    }
}

}
我想用sed命令替换connectionId中的字符串,目前我的脚本如下:

script: 'sed -e ''/connectionId/c\ \"connectionId\" : \"/subscriptions/2b06d50xxxxb-92c8-5a8939edd021/resourceGroups/Reourcetest/providers/Microsoft.Web/connections/azureblob\",'' "$(System.DefaultWorkingDirectory)/function-app-actions/templates/copycode.json"'

这个脚本可以将json文件中两个connectionId中的字符串替换为“Resourcetest”,这就是我想将第二个connectionId中的字符串替换为其他值的地方,我该怎么做呢?
我是sed命令的新手,任何见解都很感激。

编辑:

我只想将json文件中两个connectionId字符串中的“Resource1005”替换为“Resourcetest”,但我需要connectionIds字符串中的其他内容来保留以前的值
因此,我的预期输出应该如下所示:

"connectionId": "/subscriptions/2b06d502-3axxxx8939edd021/resourceGroups/Reourcetest/providers/Microsoft.Web/connections/azureblob"

"connectionId": "/subscriptions/2b06d502-3axxxx8939edd021/resourceGroups/Reourcetest/providers/Microsoft.Web/connections/office365"

如果我使用上面提到的脚本,它确实替换了两个Resource1005,但是字符串中的其他值也被替换为相同的值(我只想替换Resource1005值)

axkjgtzd

axkjgtzd1#

***第一个解决方案:***使用您显示的示例和尝试,请尝试以下GNU awk代码。这将只在输出中打印编辑过的行(根据显示的示例),并在值中用Resourcetest替换Resource1005

awk -v RS='[[:space:]]+"connectionId": "[^"]*' '
RT{
  sub(/\n+[[:space:]]+/,"",RT)
  sub(/\/Resource1005\//,"/Resourcetest/",RT)
  print RT
}
'  Input_file

***第二个解决方案:***使用sed,您可以尝试以下sed代码。

sed -nE 's/(^[[:space:]]+"connectionId": ".*)\/Resource1005\/(.*)/\1\/Resourcetest\/\2/p' Input_file
3yhwsihp

3yhwsihp2#

常见的做法是创建模板文件,然后用sed或其他命令更改它们。例如:

cat template.json
...
            "office365": {
                "connectionId": "__CONNECTIONID__",
                "connectionName": "office365",
                "id": "__ID__"
            }
...

sed 's|__CONNECTIONID__|/some/path|; s|__ID__|/some/other/path|' template.json > new.json

相关问题