Vonton
Vonton

Reputation: 3352

compare two columns in two files "awk"

I would like to compare two files for both $1,$2 column in awk. If same print all from second file and if not same print all from first file.

1st file:

a 1 2

b 2 3

c 3 4

2nd file:

a 1 2 ko lo to

b 2 3 to ho ro

result:

a 1 2 ko lo to

b 2 3 to ho ro

c 3 4

So I would like to add lines from 1st file which are not match to second file.

I wrote:

 awk -v OFS="\t" 'FNR==NR{a[$1]=$2=$3;next} {if (($1,$2) in a) print a[$1,$2,$3]; else print $0}'

but it is not work :-( Thank you.

Upvotes: 1

Views: 120

Answers (1)

karakfa
karakfa

Reputation: 67497

awk to the rescue!

$ awk '!a[$1,$2]++' file2 file1

a 1 2 ko lo to
b 2 3 to ho ro
c 3 4

this won't preserve the order though (it will print file2 contents first). Another alternative is

$ awk    '{k=$1 FS $2} 
  NR==FNR {a[k]=$0; next} 
          {print (k in a?a[k]:$0)}' file2 file1

Upvotes: 3

Related Questions