Awk Comparsion in multiple files

别来无恙 提交于 2020-01-04 07:01:11

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!