2

I would like to merge two tables:

File 1:

1 today
2 tomorrow
3 red

File 2:

1 a lot
1 sometimes
2 at work
2 at home
2 sometimes
3 new

Desired output (file 3):

1 today a lot
1 today sometimes
2 tomorrow at work
2 tomorrow at home
2 tomorrow sometimes
3 red new

I came up with the following:

awk -F '[\t]' -v OFS='\t' '{i=$1;$1=x} NR==FNR{A[i]=$0;next} A[i]{print i,$0A[i]}' file2 file1 > file3

However, it gives me only:

1 today sometimes
2 tomorrow sometimes
3 red new

7

Do you specifically require an awk solution?  join file1 file2 > file3 will do exactly what you want.

  • I like awk, but this worked, thanks! – BSP Sep 15 '14 at 17:59
6

Try:

$ awk 'FNR==NR{a[$1]=$2;next};{$1 = $1"\t"a[$1]}1' OFS='\t' file1 file2
1   today   a lot
1   today   sometimes
2   tomorrow    at  work
2   tomorrow    at  home
2   tomorrow    sometimes
3   red new
  • +1. A little terser: awk 'NR==FNR {a[$1]=$0; next} {$1=a[$1]} 1' file1 file2 – glenn jackman Sep 15 '14 at 18:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.