Compare two columns of two files and display the t

2019-09-19 13:50发布

问题:

I would like to compare the first two columns of two files file1.txt and file2.txt and if they match to write to another file output.txt with the third column of both file1,file 2 along with details if it matches or not .

file1.txt

ab|2001|name1
cd|2000|name2
ef|2002|name3
gh|2003|name4

file2.txt

xy|2001|name5
cd|2000|name6
ef|2002|name7
gh|2003|name8

output.txt

name1 name5  does not match
name2 name6  matches
name3 name7  matches
name4 name8  matches

回答1:

Welcome to stack overflow, could you please try following and let me know if this helps you.

awk -F"|" 'FNR==NR{a[$2]=$1;b[$2]=$3;next} ($2 in a) && ($1==a[$2]){print b[$2],$3,"matched properly.";next} {print b[$2],$3,"Does NOT matched."}' file1.txt file2.txt

EDIT: Adding a non-one liner form of solution too here.

awk -F"|" '
FNR==NR{
   a[$2]=$1;
   b[$2]=$3;
   next
}
($2 in a) && ($1==a[$2]){
   print b[$2],$3,"matched properly.";
   next
}
{
   print b[$2],$3,"Does NOT matched."
}
' file1.txt file2.txt


回答2:

You can use paste and awk to get what you want.

Below solution is assuming the fields in file1 and file2 will be always delimited by "|"

paste -d "|" file1.txt file2.txt | awk -F "|" '{ if( $1 == $4 && $2 == $5 ){print $3, $6, "matches"} else {print $3, $6, "does not match"} }' > output.txt


标签: shell unix