I have two files.


Dave 734.838.9800  
Bob 313.123.4567  
Carol 248.344.5576  
Mary 313.449.1390  
Ted 248.496.2204  
Alice 616.556.4458   


Bob Tuesday  
Carol Monday  
Ted Sunday   
Alice Wednesday  
Dave Thursday    
Mary Saturday  

I want to merge these two into file3.

file3 should look like:

Name      On-Call     Phone  
Carol     MONDAY      248.344.5576  
Bob       TUESDAY     313.123.4567  
Alice     WEDNESDAY   616.556.4458  
Dave      THURSDAY    734.838.9800  
Nobody    FRIDAY      634.296.3356  
Mary      SATURDAY    313.449.1390  
Ted       SUNDAY      248.496.2204  

So how can i do this in a shell script?

  • I have a one-liner which does not include the sort - awk 'BEGIN {printf("%s %10s %10s \n" ,"Name", "On-Call", "Phone")} FNR==NR{a[$1]=$2 FS $3;next}{ print $0, a[$1]}' file1.txt file2.txt | column -t – rahul Apr 19 '15 at 15:48
  • You could also look into this - stackoverflow.com/questions/23124511/…. I believe it's the same ask. – rahul Apr 19 '15 at 17:07

The join utility is intended for exactly this kind of problem: it joins two files based on one of their fields, by default the first one. The files should be sorted first; so

join <(sort file2) <(sort file1) | column -t


Alice  Wednesday  616.556.4458
Bob    Tuesday    313.123.4567
Carol  Monday     248.344.5576
Dave   Thursday   734.838.9800
Mary   Saturday   313.449.1390
Ted    Sunday     248.496.2204

This is sorted by name rather than by weekday; you'd need some post-processing to sort by weekday if necessary...

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.