问题
I have 2 files:
file1:
1,apple
2,mango
3,banana
44,orange
file2:
1,apple
22,
31,xyz
2,man
3,banana
44,oran
44,orange
I need to find the differences from both the files using column 1 and checking column 2. I don't want to use $0 as its printing the lines which of 1st file which are not present in file2 too.
Result output should be printed in file3 as :
2,mango,man
44,orange,oran
Mango is from file1 (column 2) and man is from file2 (column2)
回答1:
Slightly different awk:
$ awk 'BEGIN{FS=OFS=","}($1 in a) && a[$1]!=$2{print $1,a[$1],$2}{a[$1]=$2}' file1 file2
2,mango,man
44,orange,oran
Explained:
awk 'BEGIN {
FS=OFS="," # set separators
}
($1 in a) && a[$1]!=$2 { # if the id is in a and $2s differ (may occur only after file1
print $1,a[$1],$2 # output is already hashed into a)
}
{
a[$1]=$2 # hash to a
}' file1 file2
回答2:
Following awk may help you in same.
awk -F, 'FNR==NR{a[$1]=$0;b[$2];next} ($1 in a) && !($2 in b){print a[$1],$2}' OFS=, Input_file1 Input_file2
In case you want to take output into a file named file3 then add > file3 at last of into above command.
来源:https://stackoverflow.com/questions/48670076/awk-comparsion-in-multiple-files