【问题标题】:Terminal command to find unique pairs where order does not matter终端命令查找顺序无关紧要的唯一对
【发布时间】:2013-01-05 05:35:04
【问题描述】:

我有一个 Python 脚本 my_script.py,它会在两个元素之间生成一个以制表符分隔的配对列表,每行一个:

$ python my_script.py
cat dog
dog wolf
cat dog
pig chicken
dog cat

我希望将此脚本的输出通过管道传输到某种终端命令中,我想过滤掉重复的组合,而不仅仅是重复的排列。对于重复排列,我可以使用类似的东西:

$ python my_script.py | sort | uniq
cat dog
dog cat
dog wolf
pig chicken

删除重复的“猫狗”。 这种方法的问题是我留下了“猫狗”和“狗猫”,就我的目的而言,它们应该被视为相同(相同的组合)。我知道我可以编写另一个非常简单的 Python 脚本来执行我所追求的那种过滤,但我想看看是否有一个更简单的终端命令可以做到这一点。

【问题讨论】:

    标签: command-line awk terminal filtering


    【解决方案1】:

    这是使用awk的一种方式:

    ... | awk -F "\t" '!a[$1,$2]++ && !a[$2,$1]++'
    

    结果:

    cat dog
    dog wolf
    pig chicken
    

    解释:

    -F "\t"           # sets the field (column) separator to a single tab character
    
    !a[$1,$2]++       # adds column one and column two to a pseudo-multidimensional
                      # array if they haven't already been added to the array
    
    !a[$2,$1]++       # does the same thing, but adds the columns in the opposite
                      # orientation.
    

    总而言之:

    因此,对于每一行输入,当且仅当数组中不存在前两个字段(在任一方向)时,才会打印该行。您可以阅读有关如何模拟多维数组here 的更多信息。

    【讨论】:

    • 对于像我这样的 awk 新手用户,能否简要描述一下 awk 脚本中实际发生的情况?
    • @BryceThomas:添加了解释 :-) 如果我没有提供足够的详细信息,请告诉我。 HTH。
    【解决方案2】:

    注意:上面的脚本不会为 $1==$2 的情况提供任何输出。可以通过以下方式测试:

    echo "dog dog" | awk '!a[$1,$2]++ && !a[$2,$1]++'|wc -l
    

    试试这个:

    |awk '{if($1<$2)print $1,$2; else print $2,$1}'|sort|uniq
    

    【讨论】:

      猜你喜欢
      • 2017-05-03
      • 1970-01-01
      • 2015-06-28
      • 1970-01-01
      • 2020-09-10
      • 1970-01-01
      • 2017-11-27
      • 2011-12-11
      • 1970-01-01
      相关资源
      最近更新 更多