brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: jq limit(n; stream) stops after n results instead of reading everything

Jq
~/tips/tip-jq-limit-stop-early

jq -n -c 'limit(3; range(1; 1000000000))'

Takes only the first few results of a jq generator and quits early.

Some jq filters can produce a lot of output, and I often only want a taste. limit takes the first few results and then stops generating.

jq -n -c 'limit(3; range(1; 1000000000))'
1
2
3

The first argument is how many results you want, the second is the filter that produces them. That range would take ages to finish, yet the command returns at once because jq never asks for result number four.

It works on input as well. This reads a text stream and quits after two lines:

printf 'l1\nl2\nl3\nl4\n' | jq -n -R 'limit(2; inputs)'
"l1"
"l2"

For a plain array, the slice .[:3] is shorter and does the same. limit earns its place with generators such as .[], range, inputs and recurse.

One caveat: limit(0; ...) gives nothing at all, which is correct but looks like a broken filter when the number comes from a variable.

For a quick look at the shape of a huge file, limit(1; .[]) shows one record and nothing else.

For the common case of only wanting the first result, jq also has first(f), which behaves like limit(1; f):

echo '[1,2,3,4]' | jq -c 'first(.[]|select(.>1))'
2

The same early exit applies to infinite generators. limit(2; repeat("x")) returns "x" twice and stops, where a plain repeat would run forever.

Further reading: jq manual

More Jq tips jq -r '.files[] | @sh' data.json jq -n -c '$ARGS.positional' --args a "b c" jq 'with_entries(.key |= ascii_upcase)' jq '.replicas |= . + 1' deploy.json cut -d: -f1,7 /etc/passwd | jq -R 'split(":") | {user: .[0], shell: .[1]}' All Jq tips (20) All topics

Link