Termination of processing jq when the condition is met

I am using jq to search for specific results in a large file. I don't need duplicate entries that match this specific condition and it takes a while to process the entire file. What I would like to do is print out some details of the first match and then complete the jq command in the file to save time.

those.

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

      

I have looked at http://stedolan.github.io/jq/manual/?#Breakingoutofcontrolstructures but it doesn't quite seem like an application

EDIT: The file I am processing contains multiple json objects, one after the other. They are not in the array.

+3


source to share


2 answers


Executing the requested queries is possible using features that were added after the release of jq 1.4. The following uses foreach and input:

label $top
| foreach inputs as $line
   # state: true means found; false means not yet found
   (false;
    if . then break $top
    else if $line | tostring | test("goodbye") then true else false end
    end;
    if . then $line else empty end
   )

      

Example:



$ cat << EOF | jq -n -f exit.jq
1
"goodbye"
3
4
EOF

      

Result: "Goodbye"

0


source


Below is the approach using the latest version first/1

(currently mostly)

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

      



Quit (followed by immediate termination)

"100"

      

Here I am using seq

JSON instead of a large dataset.

0


source







All Articles