用 jq 在 json 中增加一个数值
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))"/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)
In-place 编辑
您可以使用 sponge
,或临时文件,或...(参见例如
"How can "in-place" editing of a JSON file be accomplished?"
在 jq 的 FAQ).
我有一个 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))"/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)
In-place 编辑
您可以使用 sponge
,或临时文件,或...(参见例如
"How can "in-place" editing of a JSON file be accomplished?"
在 jq 的 FAQ).