如何将jq输出中的所有数字求和 [英] How do I sum all numbers from output of jq
问题描述
我有此命令,我想对输出中的所有数字求和.
I have this command that I would like to sum all the numbers from the output.
命令如下所示
$(hadoop fs -ls -R /reports/dt=2018-08-27 | grep _stats.json | awk '{print $NF}' | xargs hadoop fs -cat | jq '.duration')
因此,它将列出/reports/dt=2018-08-27
中的所有文件夹,仅获取_stats.json
,并将其从hadoop -cat
通过jq
传递,仅从json中获取.duration
.最终我得到这样的结果.
So it's going to list all the folders in /reports/dt=2018-08-27
and get only _stats.json
and pass that through jq
from hadoop -cat
and get only .duration
from the json. Which in the end I get the result like this.
1211789 1211789 373585 495379 1211789
但是我希望命令将所有这些数字加起来成为4504331
But I would like the command to sum all those numbers together to become 4504331
推荐答案
另一种方法(即使并非所有持续时间都是整数,该方法也可以使用)是使您的jq
代码起作用:
Another option (and one that works even if not all your durations are integers) is to make your jq
code do the work:
sample_data='{"duration": 1211789}
{"duration": 1211789}
{"duration": 373585}
{"duration": 495379}
{"duration": 1211789}'
jq -n '[inputs | .duration] | reduce .[] as $num (0; .+$num)' <<<"$sample_data"
...正确发出作为输出:
...properly emits as output:
4504331
根据需要用stdin上的管道替换<<<"$sample_data"
.
Replace the <<<"$sample_data"
with a pipeline on stdin as desired.
这篇关于如何将jq输出中的所有数字求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!