Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I want to compare the information from mapping files to retrieve crosslinked information in a tab-delimited file format.

For example, one file contains

COG0001 882.DVU3168
COG0002 883.DvMF_2502
COG0001 1140.Synpcc7942_0645
COG0001 1148.SYNGTS_2220

The other file

COG0001 H
COG0002 E

The final file should contain the following information:

COG0001 882.DVU3168 H
COG0002 883.DvMF_2502   E
COG0001 1140.Synpcc7942_0645    H
COG0001 1148.SYNGTS_2220    H

EDIT

Coming back to my question, I would also like to print information from file 2 to file 3.

My command is:

awk -F $'\t' 'FNR==NR{a[$2]++;next}a[$1]''{print $0, ..... }' file2 file1 > file3

This would give me everything from file1 based on what is matching column 2 (file2) to column 1 (file1).

How to set so I can also print information from file 2?

share|improve this question

2 Answers 2

If you don't mind the order of output:

$ join <(sort file1) <(sort file2)
COG0001 1140.Synpcc7942_0645 H
COG0001 1148.SYNGTS_2220 H
COG0001 882.DVU3168 H
COG0002 883.DvMF_2502 E
share|improve this answer

With awk you could do it like this:

$ awk 'NR==FNR{a[$1]=$2;next}{print $0, a[$1]}' file2 file1
COG0001 882.DVU3168 H
COG0002 883.DvMF_2502 E
COG0001 1140.Synpcc7942_0645 H
COG0001 1148.SYNGTS_2220 H

The NR==FNR{a[$1]=$2;next} block is run for file2, and it stores the second field in a map, using the first field as a key.

The {print $0, a[$1]} block is run for file1, and it prints the current line, followed by the value retrieved from the map.

If you want the data to be tab delimited (with other whitespace not delimiting the fields), you can run awk -F'\t' ..., and if you also want the output tab delimited, use awk -F'\t' -v OFS='\t' ....

share|improve this answer
    
I just gave it a try and it worked. Now I just have to understand it so I can apply it for multiple files. Thanks alot you saved me! –  BSP Aug 9 at 14:49
    
got it..I learned to love awk :) –  BSP Aug 9 at 14:58
    
Coming back to my question, I would also like to print information from file 2 to file 3. My command is: awk -F $'\t' 'FNR==NR{a[$2]++;next}a[$1]''{print $0, ..... }' file2 file1 > file3 This would give me everything from file1 based on what is matching column 2 (file2) to column 1 (file1). How to set ...... so I can also print information from file 2? –  BSP Aug 9 at 21:22
    
@BSP What information though? Update your post with sample input/output. –  user000001 Aug 10 at 5:02

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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