Shell – How to merge two files in the same row

join;shell-scripttext processing

I have two files.

file1:

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

file2:

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?

Best Answer

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

produces

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...

Related Question