join multiple files

前端 未结 8 2012
春和景丽
春和景丽 2020-12-02 21:11

I am using the standard join command to join two sorted files based on column1. The command is simple join file1 file2 > output_file.

But how do I join 3 or more fil

8条回答
  •  情歌与酒
    2020-12-02 21:50

    Assuming you have four files A.txt, B.txt, C.txt and D.txt as:

    ~$ cat A.txt
    x1 2
    x2 3
    x4 5
    x5 8
    
    ~$ cat B.txt
    x1 5
    x2 7
    x3 4
    x4 6
    
    ~$ cat C.txt
    x2 1
    x3 1
    x4 1
    x5 1
    
    ~$ cat D.txt
    x1 1
    

    Join the files with:

    firstOutput='0,1.2'; secondOutput='2.2'; myoutput="$firstOutput,$secondOutput"; outputCount=3; join -a 1 -a 2 -e 0 -o "$myoutput" A.txt B.txt > tmp.tmp; for f in C.txt D.txt; do firstOutput="$firstOutput,1.$outputCount"; myoutput="$firstOutput,$secondOutput"; join -a 1 -a 2 -e 0 -o "$myoutput" tmp.tmp $f > tempf; mv tempf tmp.tmp; outputCount=$(($outputCount+1)); done; mv tmp.tmp files_join.txt
    

    Results:

    ~$ cat files_join.txt 
    x1 2 5 0 1
    x2 3 7 1 0
    x3 0 4 1 0
    x4 5 6 1 0
    x5 8 0 1 0
    

提交回复
热议问题