【问题标题】:Is it possible to use unique operator over a stream in jq是否可以在 jq 中的流上使用唯一运算符
【发布时间】:2019-06-04 15:11:57
【问题描述】:

以下代码

for i in {1..10}; do 
    echo '{"key":'$(($RANDOM % 3))'}'
    sleep 1 
done | jq -n '[inputs]|unique'

将打印(如果它们都出现了):

[
  {
    "key": 0
  },
  {
    "key": 1
  },
  {
    "key": 2
  }
]

问题是你需要等待10s才能看到结果(10 * sleep 1)。是否有流版本,一旦出现新元素就会将其刷新到标准输出?

【问题讨论】:

    标签: json command-line jq


    【解决方案1】:

    这是stream-oriented“唯一”的定义:

    def unique(stream):
      foreach stream as $s ({};
         ($s|type) as $t
         | ($s|tostring) as $y
         | if .[$t][$y] then .emit = false
           else .emit = true | (.item = $s) | (.[$t][$y] = true)
           end;
         if .emit then .item else empty end );
    

    您可以将它与 -n 命令行选项一起使用,如下所示:

    unique(inputs)
    

    编程笔记

    上面的“unique”面向流的版本不需要排序,从这个意义上说比内置版本更省时。

    所需的空间与不同项目的数量成线性关系。如果已知流中的项目已排序(或排列为使所有相等的项目相邻),那么下面定义的uniq 可能是有意义的。

    uniq/1

    jq Cookbookuniq 提供了这个定义,它的行为更像 Linux uniq

    def uniq(s):
      foreach s as $x (null;
        if . == null or .emitted != $x then {emit: true, emitted: $x}
        else .emit = false
        end;
        if .emit then $x else empty end);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-08
      • 2018-01-04
      • 1970-01-01
      • 2017-02-05
      • 2015-05-25
      • 2019-10-08
      • 2011-07-31
      • 2016-10-04
      相关资源
      最近更新 更多