bash:所有行组合 [英] bash: all combinations of lines

查看:84
本文介绍了bash:所有行组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下文件(此文件用分号分隔;实际文件用制表符分隔)

I have the following file (this is semicolon delimited; the real file is tab-delimited)

abc;173959;172730
def;4186657;4187943
ghi;4703911;4702577
jkl;2243551;2242259

我想将每一行与每一行合并,这样我的输出将是:

and I want to combine each line with each, so that my output would be:

abc;173959;172730;def;4186657;4187943
abc;173959;172730;ghi;4703911;4702577
abc;173959;172730;jkl;2243551;2242259
def;4186657;4187943;ghi;4703911;4702577
def;4186657;4187943;jkl;2243551;2242259
ghi;4703911;4702577;jkl;2243551;2242259

顺序并不重要.

我想出了以下awk解决方案:

I came up with the following awk-solution:

awk '{ a[$0] } END { for (i in a){ for (j in a){if (i != j)  print (i "\t" j) } } }' file

但这会向我显示两个方向的组合,例如

But this prints me the combinations in both directions, so for example

abc;173959;172730;def;4186657;4187943
def;4186657;4187943;abc;173959;172730

因为我不太熟悉python或perl,所以请使用awk/bash等寻求解决方案.

Because I am pretty unfamiliar with python or perl, I kindly ask for a solution using awk/bash etc.

推荐答案

在awk中:

$ awk '{ a[$0] }
END {
    for(i in a) {
        delete a[i]            # new place for delete
        for(j in a)
            if(i!=j)
                print i ";" j
        # delete a[i]          # previous and maybe wrong place
    }
}' file
def;4186657;4187943;ghi;4703911;4702577
def;4186657;4187943;abc;173959;172730
def;4186657;4187943;jkl;2243551;2242259
ghi;4703911;4702577;abc;173959;172730
ghi;4703911;4702577;jkl;2243551;2242259
abc;173959;172730;jkl;2243551;2242259

不幸的是,顺序是随机的.

Unfortunately the order is random.

恢复订单并且在处理时不修改a的另一种方法是(见注释)

Another way that restores the order and doesn't modify the a while processing (see comments) is:

$ awk '{ a[NR]=$0 }                  # index on NR
    END {
        for(i=1;i<=NR;i++)
            for(j=i+1;j<=NR;j++)     # j=i+1 is the magic
                print a[i] ";" a[j]
}' file
abc;173959;172730;def;4186657;4187943
abc;173959;172730;ghi;4703911;4702577
abc;173959;172730;jkl;2243551;2242259
def;4186657;4187943;ghi;4703911;4702577
def;4186657;4187943;jkl;2243551;2242259
ghi;4703911;4702577;jkl;2243551;2242259

这篇关于bash:所有行组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆