代码之家  ›  专栏  ›  技术社区  ›  bapors

查找共享信息的行

  •  1
  • bapors  · 技术社区  · 7 年前

    file1.txt 以下内容:

    1 10 20 A
    1 10 20 B
    1 10 20 E
    1 10 20 F
    1 12 22 C
    1 13 23 X
    2 33 45 D
    2 48 49 D
    2 48 49 E
    

    A
    B
    E
    F
    D
    E
    

    我只能通过以下方式计算有多少行是唯一的:

    cut -f1,2,3 file1.txt | sort | uniq | wc -l 
    5
    

    如何让第四列中的字母共享前三列?

    4 回复  |  直到 7 年前
        1
  •  2
  •   RavinderSingh13 Nikita Bakshi    7 年前

    跟随 awk

     awk 'FNR==NR{a[$1,$2,$3]++;next}  a[$1,$2,$3]>1' Input_file  Input_file
    

    输出如下。

    1 10 20 A
    1 10 20 B
    1 10 20 E
    1 10 20 F
    2 48 49 D
    2 48 49 E
    

    a[$1,$2,$3]>1 a[$1,$2,$3]>1{print $NF}'

        2
  •  2
  •   Kent    7 年前

    awk '{k=$1 FS $2 FS $3}
         k in a{a[k]=a[k]RS$4;b[k];next}{a[k]=$4}END{for(x in b)print a[x]}' file
    

    awk 'NR==FNR{a[$1,$2,$3]++;next}a[$1,$2,$3]>1{print $4}' file file
    

    在给定的示例中,上面的两个衬板提供相同的输出:

    A
    B
    E
    F
    D
    E
    

        3
  •  2
  •   karakfa    7 年前

    两全其美…

    $ awk '{print $4 "\t" $1,$2,$3}' file | uniq -Df1 | cut -f1
    
    A
    B
    E
    F
    D
    E
    

    $ rev file | uniq -Df1 | cut -d' ' -f1
    
    A
    B
    E
    F
    D
    E
    

    | rev 最后。

        4
  •  1
  •   James Brown    7 年前

    $ awk ' {
        k=$1 FS $2 FS $3        # create array key
        if(k in a) {            # a is the not-yet-printed queue
            print a[k] ORS $NF  # once printed from a...
            b[k]=$NF            # move it to b
            delete a[k]         # delete from a
        }
        else if(k in b) {       # already-printed queue
            print $NF
        } else a[k]=$NF         # store to not-yet-printed queue a
    }' file
    A
    B
    E
    F
    D
    E