我有一个 JSON 对象的集合,如下所示:
{"id":"da1234563","message":"brown fox jump over a red log"}
{"id":"da1234564","message":"brown fox jump over a red log"}
{"id":"da1234565","message":"brown fox jump over a red log"}
{"id":"da1234566","message":"brown fox jump over a red log"}
{"id":"da1234567","message":"red fox jump over a brown log"}
{"id":"da1234568","message":"another random string"}
{"id":"da1234569","message":"brown fox jump over a red log"}
我想使用
jq
迭代这些对象并返回 brown fox
的跳跃数量,直到找不到匹配项。
以下
jq
为我提供了棕色狐狸的每一行,包括最后一行:
jq -n 'inputs|select(.message|test("brown fox"))'
如何排除不匹配后的匹配项并计算匹配项的数量,以便
jq
仅返回 4
?
为了提高效率,最好避免“吸食”输入,正如 Q 中所设想的,在这种情况下可以通过使用
input
(或 inputs
)和 -n 命令行选项来非常简单地完成.
使用面向流的计数功能和内置的
while
:
def count(s): reduce s as $x (0; .+1);
count(while (inputs | .message|test("brown fox"); true) )
def count(s): reduce s as $x (0; .+1);
def select_while(s; cond):
label $out | s | if cond then . else break $out end;
count( select_while(inputs; .message|test("brown fox") ) )
另一个类似于@customcommander的选项,但使用
until
而不是reduce
:
'[0,.] |
until(
(.[1] | .[0] | .message | test("brown fox")| not);
[ .[0]+ 1 , (.[1] | .[1:]) ])
| .[0]'
与
--slurp
:
reduce .[] as $i ([0, true]; if .[1] and ($i.message | contains("brown fox")) then .[0] += 1 else .[1] = false end) | .[0]
我使用
[0, true]
来知道何时停止计数:
我确信有更好的方法,但我就是看不到;)