使用 awk 比较两个文件并打印不匹配的记录



我正在比较两个文件 file1 和 file2,我需要打印在 file1 中比较的文件 2 的更新记录。 我需要更改文件2和新添加的记录的数据

文件1:

1|footbal|play1
2|cricket|play2
3|tennis|play3
5|golf|play5

文件2:

1|footbal|play1
2|cricket|play2
3|tennis|play3
4|soccer|play4
5|golf|play6

输出文件:

4|soccer|play4
5|golf|play6

我已经尝试了以下解决方案,但它不是预期的输出

awk -F'|' 'FNR == NR { a[$3] = $3; a[$1]=$1; next; } { if ( !($3 in a) && !($1 in a) ) { print $0; } }' file1.txt file2.txt

我已经比较了两个文件中的列 1 和列 3

你能试试下面的吗?

awk 'BEGIN{FS="|"}FNR==NR{a[$1,$3];next} !(($1,$3) in a)' Input_file1  Input_file2

或非一种衬里形式的溶液。

awk '
BEGIN{
FS="|"
}
FNR==NR{
a[$1,$3]
next
}
!(($1,$3) in a)
'  Input_file1  Input_file2

说明:为上述代码添加详细说明。

awk '               ##Starting awk program from here.
BEGIN{              ##Starting BEGIN section of this program from here.
FS="|"            ##Setting FS as pipe here as per Input_file(s).
}                   ##Closing BEGIN block for this awk code here.
FNR==NR{            ##Checking condition FNR==NR which will be TRUE when 1st Input_file named file1 is being read.
a[$1,$3]          ##Creating an array named a with index os $1,$3 of current line.
next              ##next will skip all further statements.
}
!(($1,$3) in a)     ##Checking condition if $1,$3 are NOT present in array a then print that line from Input_file2.
'  Input_file1  Input_file2     ##mentioning Input_file names here.

输出将如下所示。

4|soccer|play4
5|golf|play6

最新更新