繁体   English   中英

使用bash打印列中的常用值

[英]Print common values in columns using bash

我有两列文件

apple apple
ball cat
cat hat
dog delta

我需要提取两列(在两列中都出现)相同的值

apple apple
cat cat 

每列中的项目均无顺序。

您能否尝试遵循并让我知道这是否对您有帮助。

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

注意:如果在两列中找到的值也出现在两列中的次数恰好相同,它将打印这些值。

假设我可以使用unix命令:

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

基本上,这是这样的:

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

第一个cut命令使用列表中第二个单词列,并将它们通过管道传递到启用了regexp的egrep命令中。

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

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

要么

gawk '$1==$2 {print $1,"=",$2}' file.txt
$ 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM