AWK Script For Merging Text Files

Hello,

I am trying to merge data from two text files. One file (File1) contains a listing of data which includes the trial number in Column 5, while the other text file (File2) contains what category the trial belongs to.

Here is a snippet of what File1 looks like.

1 Arrow_ST 9.738 0.905 1
1 Arrow_Gamble 10.703 0.188 1
1 Gamble_Loss 14.247 0.292 2
1 Gamble_Win 14.578 0.151 2

And here is a snippet of what File2 looks like:

1 Gamble
2 SureThing

In other words, for all of Trial 1 (i.e., the first two snippet lines of File1) belong to the category "Gamble", all of Trial 2 (i.e., the last two snippet lines of File2) belong to the category "SureThing", and so on.

What I want to do is merge the two, so that an additional column is created in File1 that lists the category membership for each trial. So, my output should look as follows:

1 Arrow_ST 9.738 0.905 1 Gamble
1 Arrow_Gamble 10.703 0.188 1 Gamble
1 Gamble_Loss 14.247 0.292 2 SureThing
1 Gamble_Win 14.578 0.151 2 SureThing

Any help or nudges in the right direction would be greatly appreciated. Thanks!

-Jahn

awk 'NR == FNR { 
  cat[$1] = $2; next 
  }
{ 
  print $0, cat[$5]
  }' file2 file1
#!/bin/bash


awk 'BEGIN{
while ( ( getline < "file2" ) > 0){
   array_test[$1]=$0
}
}


{
print $1 " " $2 " " $3 " " $4 " " array_test[$5]
}' file1

a simple use of associative arrays :slight_smile: