nhereveri
nhereveri

Reputation: 143

AWK replace $0 of second file when match few columns

How I merge two files when two first columns match in both files and replace first file values with second file columns... I mean...

Same number of columns:

FILE 1:
121212,0100,1.1,1.2,
121212,0200,2.1,2.2,

FILE 2:
121212,0100,3.1,3.2,3.3,
121212,0130,4.1,4.2,4.3,
121212,0200,5.1,5.2,5.3,
121212,0230,6.1,6.2,6.3,

OUTPUT:
121212,0100,3.1,3.2,3.3,
121212,0200,5.1,5.2,5.3,

In other words, I need to print $0 of the second file when match $1 and $2 in both files. I understand the logic but I can't implement it using arrays. That apparently should be used.

Please take a moment to explain any code.

Upvotes: 1

Views: 419

Answers (2)

Steve
Steve

Reputation: 54542

Here's one way using awk:

awk -F, 'FNR==NR { a[$1,$2]; next } ($1,$2) in a' file1 file2

Results:

121212,0100,3.1,3.2,3.3,
121212,0200,5.1,5.2,5.3,

Upvotes: 1

Chris Seymour
Chris Seymour

Reputation: 85875

Use awk to print the first 2 fields in the pattern file and pipe to grep to do the match:

$ awk 'BEGIN{OFS=FS=","}{print $1,$2}' file1 | grep -f - file2
121212,0100,3.1,3.2,3.3,
121212,0200,5.1,5.2,5.3,

The -f option tells grep to take the pattern from a file but using - instead of a filename makes grep take the patterns from stdin.

So the first awk script produces the patterns from file1 which we pipe to match against in file2 using grep:

$ awk 'BEGIN{OFS=FS=","}{print $1,$2}' file1
121212,0100
121212,0200

You probably want to anchor the match to the beginning of the line using ^:

$ awk 'BEGIN{OFS=FS=","}{print "^"$1,$2}' file1 
^121212,0100
^121212,0200

$ awk 'BEGIN{OFS=FS=","}{print "^"$1,$2}' file1 | grep -f - file2
121212,0100,3.1,3.2,3.3,
121212,0200,5.1,5.2,5.3,

Upvotes: 2

Related Questions