[英]increment a numerical value in a json with jq
我有一個看起來像這樣的json:-
{
"name": "abc",
"version": "20.02.01",
"tag": "24",
"abc_version": "20.02",
"registry": "registry.abc.com",
"vendor": "greenplanet",
"apps": [
{
"name": "abc-app",
"version": "20.02.01-16",
"volumes": [
"/dev/log:/dev/log"
],
"max_instances": "1"
},
{
"name": "xyz-app",
"version": "2.0.0-2",
"volumes": [
"/dev/log:/dev/log"
],
"max_instances": "1"
}
]
}
基於我需要增加 abc-app 或 xyz-app 版本的條件。 目前 abc-app 為“20.02.01-16”,我需要將其更改為“20.02.01-17”。 此外,我需要將父應用程序的標簽“abc”增加到“25”,我可以使用 sed 增加版本,但這對我不起作用:-
./jq -r ".apps" version.json | ./jq -r ".[] | .version" | grep -v '1.0.2' |sed -r 's/([0-9]+.[0-9]+.[0-9]+)(.*)([0-9]+)/echo "\1\2$((\3+1))"/e'
我需要在 json 中就地增加上述所有條件,或者可能到一個臨時文件中,我可以將其移動到原始文件中。
先感謝您。
首先,讓我們定義一個輔助函數來執行增量:
# return a string
def inc:
(capture("(?<pre>.*)-(?<post>[0-9]+$)") | "\(.pre)-\( (.post|tonumber) + 1 )")
// "\(tonumber+1)" ;
解決方案的其余部分現在可以寫成兩行,每行一行表示要遞增的值:
.tag |= inc
| .apps |= map(if .name == "abc-app" then .version |= inc else . end)
您可以使用sponge
,或臨時文件,或...(參見例如"How can "in-place" editing of a JSON file be accomplished?"
對"How can "in-place" editing of a JSON file be accomplished?"
在 jq 的常見問題解答中)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.