You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Shell脚本中使用jq更新文件中指定键的对应值

问题:更新JSON Lines文件中指定键的值

场景说明

我有一个JSON Lines格式的文件pair.json,内容如下:

{ "test": "10" }
{ "games": "30" }
{ "REPOSITORY": "5"}

想要实现的效果是:只更新原有games键所在对象的值,比如改成66,其他对象保持不变,最终文件应该是:

{ "test": "10" }
{ "games": "66" }
{ "REPOSITORY":"5"}

错误尝试及问题

之前用了以下jq命令:

tmp=$(mktemp);
jq '.games = "66"' pair.json > "$tmp" && mv "$tmp" change.json

结果所有对象都被强制添加了games键,输出变成:

{
  "test": "10",
  "games": "66"
}
{
  "games": "66"
}
{
  "REPOSITORY": "5",
  "games": "66"
}

正确解决方法

基础固定值更新

用jq的has()函数判断对象是否包含目标键,只对符合条件的对象修改值,命令如下:

tmp=$(mktemp);
jq 'if has("games") then .games = "66" else . end' pair.json > "$tmp" && mv "$tmp" change.json

执行后就能得到预期结果:只有原本带games的对象被修改,其他对象保持原样。

结合bash变量更新(后续扩展)

如果需要通过bash变量传递新值,用--arg参数实现,示例如下:

new_games_value="66"
tmp=$(mktemp);
jq --arg val "$new_games_value" 'if has("games") then .games = $val else . end' pair.json > "$tmp" && mv "$tmp" change.json

内容的提问来源于stack exchange,提问作者Humble

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 17:05:30