Awk to merge two files using hash

1

I have two files of the same length, and I want to swap out one files 3 columns with another file's contents. I want to print the following:

f1Col1 f1Col2 f1Col3 f1Col4 f1Col5 f1Col6 f2Col1 f2Col2 f2Col3 f1Col10 f1Col11 f1Col12

where f1Col1 is the first column of file1, etc.

I tried to use the following:

awk 'NR==FNR {h1[$1] = $1; h2[$2] = $2; h3[$3] = $3; next} {print $1,$2,$3,$4,$5,$6,h1[$1],h2[$2],h3[$3],$10,$11,$12}' file2 file1

which prints all the necessary columns from file1 but prints blanks instead of the columns from file2. What's wrong here?

(note: I'm using OS X Yosemite)

sodiumnitrate

Posted 2015-04-20T00:34:16.997

Reputation: 296

Do you want to use only awk, or are other commands allowed as well? – Vincent – 2015-04-20T02:09:53.473

I was curious why it didn't work. – sodiumnitrate – 2015-04-20T21:42:57.177

Answers

1

If file2 contains (for example)

The    quick    brown
fox    jumps    over
the    lazy     dog.

then the first part of your awk script is setting

h1["The"]="The"
h2["quick"]="quick"
h3["brown"]="brown"
h1["fox"]="fox"
h2["jumps"]="jumps"
h3["over"]="over"
h1["the"]="the"
h2["lazy"]="lazy"
h3["dog."]="dog."

This doesn’t do you any good when you try to use those saved values in the second part of the script; you need to index the arrays by line number:

h1[1]="The"
h2[1]="quick"
h3[1]="brown"
h1[2]="fox"
h2[2]="jumps"
h3[2]="over"
h1[3]="the"
h2[3]="lazy"
h3[3]="dog."

So your script needs to be

awk 'NR==FNR {h1[FNR] = $1; h2[FNR] = $2; h3[FNR] = $3; next}
{print $1,$2,$3,$4,$5,$6,h1[FNR],h2[FNR],h3[FNR],$10,$11,$12}' file2 file1

Scott

Posted 2015-04-20T00:34:16.997

Reputation: 17 653

1

What about:

paste <(awk'{ print $1,$2,$3,$4,$5,$6 }' file1) <(awk '{ print $1,$2,$3 }' file2) <(awk '{ print $10,$11,$12 }' file1) 
  • paste takes input from the individual awk commands
  • by placing the awk commands in between '<( )', only the standard output is read
  • paste merges the three output files row by row

Vincent

Posted 2015-04-20T00:34:16.997

Reputation: 930

1We’re looking for substantial answers that provide some explanation and context.  Don’t just give a one-line answer; explain why your answer is right.  Answers that don’t include explanations may be removed. – G-Man Says 'Reinstate Monica' – 2015-04-20T04:23:30.113

2Could you please [edit] your answer to give an explanation of why this code answers the question? – DavidPostill – 2015-04-20T05:35:48.793