Search and merge multiple files in UNIX

2019-08-30 17:42发布

问题:

I have multiple .dat files, which i will get to know dynamically. dat file will have two columns seperated by comma. Will be like key value pairs. For example:

File1:                
entry1,100             
entry2,200            
entry3,300

File2:                    
entry1,500                 
entry3,750

Now I want the output as

File3:           
entry1,100,500                 
entry2,200                
entry3,300,750  

回答1:

Assuming you want to include unpairable lines from both files - such as entry2,200 from File2 the following command should work:

join -t, -a1 -a2 file1 file2

-t, instructs join to use comma as a delimiter, -a1 -a2 instructs join to include unpairable lines from each file.



回答2:

You can use awk when input files are not already sorted:

awk 'BEGIN{FS=OFS=","} FNR==NR{a[$1]=$2; next} {print $0 (($1 in a)?OFS a[$1]:"")}' f2.dat f1.dat
entry1,100,500
entry2,200
entry3,300,750


标签: shell unix