我们要根据以下规则编辑json文件
我们需要生成 name car0X_hyb.com
-undermazda
字符串(而 X 是 ID 号)
我们需要更新 Linux 机器上的 json 文件
例子 - ID=1
那么 json 将是
{
"toyota": [
"car1.com"
],
"mazda": [
"car01_hyb.com"
],
"ford": [
"car01_eng.com"
]
}
ID=4
, 那么 json 将是
{
"toyota": [
"car1.com"
],
"mazda": [
"car01_hyb.com",
"car02_hyb.com",
"car03_hyb.com",
"car04_hyb.com"
],
"ford": [
"car01_eng.com"
]
}
ID=6
, 那么 json 将是
{
"toyota": [
"car1.com"
],
"mazda": [
"car01_hyb.com",
"car02_hyb.com",
"car03_hyb.com",
"car04_hyb.com",
"car05_hyb.com",
"car06_hyb.com"
],
"ford": [
"car01_eng.com"
]
}
ID=10
, 那么 json 将是
{
"toyota": [
"car1.com"
],
"mazda": [
"car01_hyb.com",
"car02_hyb.com",
"car03_hyb.com",
"car04_hyb.com",
"car05_hyb.com",
"car06_hyb.com",
"car07_hyb.com",
"car08_hyb.com",
"car09_hyb.com",
"car10_hyb.com"
],
"ford": [
"car01_eng.com"
]
}
答案1
似乎没有一种不丑陋的方法来对 ID 进行零填充,但是考虑到
$ jq '.' file.json
{
"toyota": [
"car1.com"
],
"mazda": [
"foo.bar"
],
"ford": [
"car01_eng.com"
]
}
然后例如对于ID
= 11
:
$ jq --arg ID 11 '
.mazda |= [range(1;($ID | tonumber)+1) as $ID | if $ID < 10 then "car0\($ID)_hyb.com" else "car\($ID)_hyb.com" end]
' file.json
{
"toyota": [
"car1.com"
],
"mazda": [
"car01_hyb.com",
"car02_hyb.com",
"car03_hyb.com",
"car04_hyb.com",
"car05_hyb.com",
"car06_hyb.com",
"car07_hyb.com",
"car08_hyb.com",
"car09_hyb.com",
"car10_hyb.com",
"car11_hyb.com"
],
"ford": [
"car01_eng.com"
]
}
或者(也许这更好)在 shell 中生成并格式化完整的字符串元素,并将其作为argjson
:
jq --argjson IDS '['"$(seq -s, -f'"car%02.0f_hyb.com"' 11)"']' '
.mazda |= $IDS
' file.json