Matching first 2 columns..

Hello All,

I want to make a file which will have primarily lines of file2 but when first 2 fields matches with the file1 it should have those lines of file1..

example is as below..

file1

a;b;1
c;d
f;e
t;r;5

file2

b;g
a;b
c;d
v;b
f;e
t;r

I want to make it like

b;g
a;b;1
c;d
v;b
f;e
t;r;5

I tried several options with join, cut & paste but did not work.. :confused:

BR
Nil

Hello,

Following may help you in same.

awk -F";" 'FNR==NR{X[$1 FS $2]=$3;next} ($1 FS $2){if(X[$1 FS $2]){print $1 FS $2 FS X[$1 FS $2]} else {print $1 FS $2}}' File1 File2

Output will be as follows.

b;g
a;b;1
c;d
v;b
f;e
t;r;5

Thanks,
R. Singh

1 Like

You could also try something like:

awk '
BEGIN {	FS = OFS = ";"
}
FNR == NR {
	a[$1,$2] = $0
	next
}
($1,$2) in a {
	$0 = a[$1,$2]
}
1' file1 file2

which produces the output you requested.

If you want to try this on a Solaris/SunOS system, change awk to /usr/xpg4/bin/awk , /usr/xpg6/bin/awk , or nawk .

1 Like