0

I can reduce produced lines like:

seq 5 | jq --slurp ' reduce .[] as $i (0;.+($i|tonumber))'

to get

15

but this put whole input into memory, I don't want that. Following:

seq 5 | jq ' reduce . as $i (0;.+($i|tonumber))'

produces incorrect output

1
2
3
4
5

similar happens when foreach is used.

What is correct syntax?

Martin Mucha
  • 2,385
  • 1
  • 29
  • 49
  • Note a dupe, but related: [Difference between slurp, null input, and inputs filter](https://stackoverflow.com/q/73843868/112968) – knittl Dec 05 '22 at 17:57

1 Answers1

0

Use inputs instead of the context ., along with the --null-input (or -n) option so the context wouldn't eat up the first item:

seq 5 | jq -n 'reduce inputs as $i (0;.+($i|tonumber))'
15

Demo

Explanation: If you just use . as context, your filter will be executed once for each input (five times in this case, hence five outputs, each summing up just one value). Providing the -n option sets the input to null, so the filter is executed only once, while input and inputs sequentially read in another/all new items from the input stream.

pmf
  • 24,478
  • 2
  • 22
  • 31