比较两个文件并仅打印不匹配的行的第一个单词以及字符串

比较两个文件并仅打印不匹配的行的第一个单词以及字符串

我想比较两个文件并仅打印匹配行和不匹配行的第一个单词以及字符串。

file1.txt
=========

abc 123
bcd 234
cde 345

file2.txt
=========

abc 123
bcd 223
cde 234

上面的 abc 在 file1.txt 和 file2.txt 中都匹配。所以我需要打印如下:

abc is matching. it is ok.

上面file1.txt和file2.txt中的bcd和cde没有区别。所以我需要打印如下:

bcd is not matching. please check.
cde is not matching. please check.

答案1

awk

awk 'NR==FNR{a[$1]=$2; next}; $2==a[$1] {print $1 " OK"; next} \
                                        {print $1 " Not OK"}' f1.txt f2.txt
  • NR==FNR仅适用于第一个文件,f1.txt此处;我们正在创建数组a,其中第一个字段作为键,第二个字段作为值,next转到下一条记录,而无需进一步向下移动条件

  • $2==a[$1]检查第二个文件的第二个字段是否与f2.txt数组的第一个键字段的值匹配a,然后以所需的格式打印

例子:

% cat f1.txt
abc 123
bcd 234
cde 345

% cat f2.txt
abc 123
bcd 223
cde 234

% awk 'NR==FNR{a[$1]=$2; next}; $2==a[$1] {print $1 " OK"; next} {print $1 " Not OK"}' f1.txt f2.txt
abc OK
bcd Not OK
cde Not OK

答案2

awk 'NR==FNR{A[NR]=$0;next}{if($0==A[FNR]){print $0 "is matching. it is ok"}else{print $0 "is not matching. please check"}}' file1.txt file2.txt

可读格式

awk 'NR==FNR{
A[NR]=$0;
next
}
{
if($0==A[FNR])
{
    print $0 "is matching. it is ok"
}
else{
print $0 "is not matching. please check"
}
}' file1.txt file2.txt

答案3

代码@Kamaraj 已更新。请您需要更换线路:

print $0 "is matching. it is ok"
print $0 "is not matching. please check"

经过

split($0,a,/ /); print a[1] " is matching. it is ok"
split($0,a,/ /);print a[1] " is not matching. please check"

或 print $1 "匹配。没问题" print $1 "不匹配。请检查"

所有脚本将是:

awk 'NR==FNR{
A[NR]=$0;
next
}
{
if($0==A[FNR])
{
split($0,a,/ /); print a[1] " is matching. it is ok"
}
else{
split($0,a,/ /);print a[1] " is not matching. please check"
}
}' file1.txt file2.txt

时间:

@heemayl真实0m0.159s用户0m0.000s系统0m0.046s

@Kamaraj真实0m0.102s用户0m0.000s系统0m0.031s与分裂

@Kamaraj真实0m0.099s用户0m0.000s系统0m0.062s1 美元

谢谢@Kamaraj。

相关内容