[英]AWK Compare 2 columns in 2 files, print if one is equal while other is not
如果两个文件中的第一列都匹配,但第3列不匹配,我将尝试打印文件一+文件二中列3的所有行。
例:
File1
John 12 Mango
David 13 Apple
Jack 14 Orange
File2
John 12 Grape
David 13 Apple
Jack 14 Apple
产量
John 12 Mango Grape
Jack 14 Orange Apple
我尝试了不同的awk命令,但是当两个列都匹配时它们可以工作,但是当只有一个列匹配而其他列不匹配时,我需要打印。 我对脚本和Unix命令还很陌生,对于所提出的解决方案,我将不甚解释。
$ awk 'NR==FNR{a[$1]=$3; next} ($1 in a) && (a[$1] != $3){print $0, a[$1]}' file2 file1
John 12 Mango Grape
Jack 14 Orange Apple
awk解决方案:
$ cat tst.awk
NR==FNR { a[$1" "$2]=$3; next }
{ s=$1" "$2;
if (s in a && a[s] != $3)
printf("%s %s %s\n", s, a[s], $3)
}
运行:
$ awk -f tst.awk input1.txt input2.txt
John 12 Mango Grape
Jack 14 Orange Apple
编辑通用版本:匹配列1和列col中的不匹配
$ cat tst2.awk
BEGIN {col=3}
NR==FNR { a[$1]=$0; next }
$1 in a {
split(a[$1],b," ");
if ($col!=b[col])
print a[$1], $col
}
您甚至可以从awk文件中删除BEGIN
并添加变量col命令行,如下所示:
$ awk -v col=3 -f tst2.awk input1.txt input2.txt
John 12 Mango Grape
Jack 14 Orange Apple
粘贴 + awk方法:
paste <(sort file1) <(sort file2) | awk '$1==$4 && $3!=$6{ print $1,$2,$3,$6 }'
输出:
Jack 14 Orange Apple
John 12 Mango Grape
如果您需要通用解决方案,请遵循简单的Perl脚本(约30行),它应适用于文件中任意数量的列以及作为输入参数给出的匹配/不匹配的列号-
use strict;
my @f1; my @f2;
open F, config()->{file1} or die $!;
while (<F>){
chomp;
next unless /\S+/;
push @f1, [ split /\s+/ ];
}
close F;
open F, config()->{file2} or die $!;
while (<F>){
chomp;
next unless /\S+/;
push @f2, [ split /\s+/ ];
}
close F;
my $c1 = config()->{'match_col_num'}-1;
my $c2 = config()->{'mismatch_col_num'}-1;
for my $l1 (@f1){
for my $l2 (@f2){
if ($l1->[$c1] eq $l2->[$c1] and $l1->[$c2] ne $l2->[$c2]){
print join " ", (@{$l1}, $l2->[$c2]);
print "\n";
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.