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 have a file a:

aaa  bbb  ccc  DDD  
ads  zzz  caa  DDD  
aba  bab  cac  DAD  
aad  cca  cas  SFD  

and a file b:

DDD  5  
DAD  13  
SFD  11

I want to add a fifth column to file a based on file b, meaning search the term of column4 of file a in file b and add a fifth column to file a containing the respective value of column2 in file b.

Can you help me?

share|improve this question
    
Ah ja, file a also has headers. So I would like to add the fith column also with a header (e.g. 'value'). –  user30012 Jan 10 '13 at 15:03
    
What is the language you need? In bash it looks some weird. Python, perl or R fit besser. –  dchirikov Jan 10 '13 at 15:11
    
Are strings in 1st column in file b unique? How many lines it has? –  dchirikov Jan 10 '13 at 15:13
    
In principle the language does not matter, R I know a bit, so this is easiest. –  user30012 Jan 10 '13 at 15:44
    
yes, the strings in col 1 in file b are unique –  user30012 Jan 10 '13 at 15:45
add comment

1 Answer 1

join -o 1.1,1.2,1.3,1.4,2.2 -1 4 -2 1 <(sed '1d' file1 | sort -k4) <(sed '1d' file2 | sort)

sed '1d' is used to strip the header (1 line from the top)

then we join the first file on field 4 with the second file on field 1

also the files must be sorted for join to work properly so we sort file1 on the field it is joined on

the -o is the order in which to print the output N.M (where N=file and M=field)

share|improve this answer
    
thanks, this worked! –  user30012 Jan 10 '13 at 15:56
1  
dont forget to check the check box to accept the answer –  h3rrmiller Jan 10 '13 at 20:16
add comment

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.