join multiple files

2020-02-08 02:40发布

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 files using the same technique ? join file1 file2 file3 > output_file Above command gave me an empty file. I think sed can help me but I am not too sure how ?

标签: linux join sed
8条回答
何必那么认真
2楼-- · 2020-02-08 03:05

I created a function for this. First argument is the output file, rest arguments are the files to be joined.

function multijoin() {
    out=$1
    shift 1
    cat $1 | awk '{print $1}' > $out
    for f in $*; do join $out $f > tmp; mv tmp $out; done
}

Usage:

multijoin output_file file*
查看更多
混吃等死
3楼-- · 2020-02-08 03:06

I know this is an old question but for future reference. If you know that the files you want to join have a pattern like in the question here e.g. file1 file2 file3 ... fileN Then you can simply join them with this command

cat file* > output

Where output will be the series of the joined files which were joined in alphabetical order.

查看更多
家丑人穷心不美
4楼-- · 2020-02-08 03:19

Join joins lines of two files on a common field. If you want to join more - do it in pairs. Join first two files first, then join the result with a third file etc.

查看更多
beautiful°
5楼-- · 2020-02-08 03:19

One can join multiple files (N>=2) by constructing a pipeline of joins recursively:

#!/bin/sh

# multijoin - join multiple files

join_rec() {
    if [ $# -eq 1 ]; then
        join - "$1"
    else
        f=$1; shift
        join - "$f" | join_rec "$@"
    fi
}

if [ $# -le 2 ]; then
    join "$@"
else
    f1=$1; f2=$2; shift 2
    join "$f1" "$f2" | join_rec "$@"
fi
查看更多
男人必须洒脱
6楼-- · 2020-02-08 03:20

The man page of join states that it only works for two files. So you need to create and intermediate file, which you delete afterwards, i.e.:

> join file1 file2 > temp
> join temp file3 > output
> rm output
查看更多
一纸荒年 Trace。
7楼-- · 2020-02-08 03:24

While a bit an old question, this is how you can do it with a single awk:

awk -v j=<field_number> '{key=$j; $j=""}  # get key and delete field j
                         (NR==FNR){order[FNR]=key;} # store the key-order
                         {entry[key]=entry[key] OFS $0 } # update key-entry
                         END { for(i=1;i<=FNR;++i) {
                                  key=order[i]; print key entry[key] # print
                               }
                         }' file1 ... filen

This script assumes:

  • all files have the same amount of lines
  • the order of the output is the same order of the first file.
  • files do not need to be sorted in field <field_number>
  • <field_number> is a valid integer.
查看更多
登录 后发表回答