0

I have two files:

File1

212 21  24.8    13.8354303  15.2841303
258 21  22.2    15.8507278  17.2994278
270 21  27.8    13.0482192  14.4969192
204 21  22.4    13.9465939  15.3952939
248 21  16.6    9.2714745   11.6494745
279 21  22.8    12.9151566  15.2931566

File2

212 21  24.8    1.03    2.8954
258 21  22.2    1.03    2.8954
270 21  27.8    1.05    2.9154
204 21  22.4    1.21    3.0754
248 21  16.6    1.29    3.1554
279 21  22.8    1.47    3.3354

and I must to join both in this way:

212 21  24.8    13.8354303  15.2841303  1.03    2.8954
258 21  22.2    15.8507278  17.2994278  1.03    2.8954
270 21  27.8    13.0482192  14.4969192  1.05    2.9154
204 21  22.4    13.9465939  15.3952939  1.21    3.0754
248 21  16.6    9.2714745   11.6494745  1.29    3.1554
279 21  22.8    12.9151566  15.2931566  1.47    3.3354

but, I used this awk command:

awk 'NR==FNR{a[$1]=$4 FS $5;next}$1 in a{print $1,$2,$3,$4,$5,a[$1]}'  File2 File1 > output

and I got this file:

output

212 21  24.8    13.8354303  15.2841303
1.03    2.8954          
258 21  22.2    15.8507278  17.2994278
1.03    2.8954          
270 21  27.8    13.0482192  14.4969192
1.05    2.9154          
204 21  22.4    13.9465939  15.3952939
1.21    3.0754          
248 21  16.6    9.2714745   11.6494745
1.29    3.1554          
279 21  22.8    12.9151566  15.2931566
1.47    3.3354          

I don't know what I did wrong, my files have about 400 rows.

  • 2
    Are the files in DOS format with an embedded ^M at the end of each line? If so, you should run dos2unix first – Stephen Harris Aug 8 '16 at 16:25
3

Assuming the data is sorted, for the type of situation I would use the join command

join -o 1.1 1.2 1.3 1.4 1.5 2.4 2.5 file1.txt file2.txt 
212 21 24.8 13.8354303 15.2841303 1.03 2.8954
258 21 22.2 15.8507278 17.2994278 1.03 2.8954
270 21 27.8 13.0482192 14.4969192 1.05 2.9154
204 21 22.4 13.9465939 15.3952939 1.21 3.0754
248 21 16.6 9.2714745 11.6494745 1.29 3.1554
279 21 22.8 12.9151566 15.2931566 1.47 3.3354

You use -o to set the format in a x.y style where x is the file and y is the field.

0

Please note that for join correct result both file1 and file2 should be previously sorted by first field.
If there is not a case and you want to keep order

awk '
    FNR==NR{a[$1]=$4 OFS $5; next}
    $1 in a{print $0, a[$1]}
    ' OFS='\t' file2 file1

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.