Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terminating jq processing when condition is met

Tags:

jq

I am using jq to search for specific results in a large file. I do not care for duplicate entries matching this specific condition, and it takes a while to process the whole file. What I would like to do is print some details about the first match and then terminate the jq command on the file to save time.

I.e.

jq '. | if ... then "print something; exit jq" else ... end'

I looked into http://stedolan.github.io/jq/manual/?#Breakingoutofcontrolstructures but this didn't quite seem to apply

EDIT: The file I am parsing contains multiple json objects, one after another. They are not in an array.

like image 429
curious-me Avatar asked Jul 27 '15 16:07

curious-me


1 Answers

Here is an approach which uses a recent version of first/1 (currently in master)

def first(g): label $out | g | ., break $out; 

first(inputs | if .=="100" then . else empty end)

Example:

$ seq 1000000000 | jq -M -Rn -f filter.jq

Output (followed by immediate termination)

"100"

Here I use seq in lieu of a large JSON dataset.

like image 114
jq170727 Avatar answered Oct 10 '22 10:10

jq170727