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

使用bash打印列中的公共值

  •  0
  • marc  · 技术社区  · 7 年前

    我有两栏的文件

    apple apple
    ball cat
    cat hat
    dog delta
    

    我需要提取两列中常见的值(出现在两列中),比如

    apple apple
    cat cat 
    

    每列中的项目没有排序。

    4 回复  |  直到 7 年前
        1
  •  0
  •   karakfa    7 年前
    $ awk '{a[$1];b[$2]} END{for(k in a) if(k in b) print k}' file
    apple
    cat
    

    要打印两次值,请更改为 print k,k

    具有 sort/join

    $ join <(cut -d' ' -f1 file | sort) <(cut -d' ' -f2 file | sort)
    apple
    cat
    

    也许,

    $ function f() { cut -d' ' -f"$1" file | sort; }; join <(f 1) <(f 2)
    
        2
  •  1
  •   RavinderSingh13 Nikita Bakshi    7 年前

    你能试着跟我说一下吗?如果这对你有帮助的话,请告诉我。

    awk '
    {
      col1[$1]++;
      col2[$2]++;
    }
    END{
      for(i in col1){
        if(col2[i]){
          while(++count<=(col1[i]+col2[i])){
             printf("%s%s",i,count==(col1[i]+col2[i])?ORS:OFS)}
          count=""}
      }
    }' Input_file
    

    注: 如果在这两列中都找到值,那么它也将打印这些值在这两列中出现的确切次数。

        3
  •  0
  •   mankowitz    7 年前

    假设我可以使用unix命令:

    cut -d' ' -f2 fil | egrep `cut -d' ' -f1 < fil | paste -sd'|'` -
    

    基本上是这样的:

    第二个 cut 命令收集第一列中的所有单词。这个 paste 命令将它们与管道(即 dog|cat|apple )。

    第一个 命令获取列表中的第二列单词,并将其导入启用了regexp的 egrep 命令。

        4
  •  0
  •   James Leveille    7 年前

    这是我能得到的最接近的。也许您可以遍历整个文件,并在到达另一个事件时进行打印。

    代码

    cat file.txt | gawk   '$1==$2 {print $1,"=",$2}'
    

    gawk '$1==$2 {print $1,"=",$2}' file.txt