You need to enable JavaScript to run this app. 如何在现有jq命令输出末尾添加金额总和,支持jq或shell实现?
优惠活动
大模型
产品
解决方案
定价
更多

如何在现有jq命令输出末尾添加金额总和,支持jq或shell实现?

方案1:纯jq单命令实现

直接修改原有jq命令即可,仅需新增预计算总金额的逻辑,用jq的逗号操作符同时输出数组和总和行:

cat example-data.json | 
  jq -Ccr '
    # 预计算总金额(单位转换为美元)
    (.data | map(.total) | add / 100) as $total
    # 原有格式化+排序逻辑输出发票列表
    | [.data[] 
        | {invoice_id: .id, client: .customer_name, date: .date | strftime("%Y-%m-%d"), amount: .total, status: .status}
        | .amount = "$" + (.amount/100|tostring)]
      | sort_by(.date),
      # 输出总和行
      "Total: \($total)"
  '

参数-r会自动去掉字符串的外层引号,保证总和行输出不带多余格式,全程仅需读取一次数据文件,执行效率更高。

方案2:Bash拼接实现

如果不想调整原有成熟的jq查询逻辑,可以分两步处理:

#!/bin/bash
# 第一步:输出原有格式化发票列表
cat example-data.json | 
  jq -C '[.data[] 
          | {invoice_id: .id, client: .customer_name, date: .date | strftime("%Y-%m-%d"), amount: .total, status: .status}
          | .amount = "$" + (.amount/100|tostring)]
         | sort_by(.date)'
# 第二步:单独计算总金额并输出
total=$(cat example-data.json | jq '[.data[].total] | add / 100')
echo "Total: \$$total"

这种方案逻辑拆分清晰,适合需要后续单独使用总金额做其他业务处理的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 01:27:04