LoginSignup
0
0

More than 5 years have passed since last update.

awkによるcsvファイル結合スクリプト

Last updated at Posted at 2017-10-05

用途/特長

同じ行数のcsvファイルが前提ですが、任意の数のcsvファイルを水平方向に結合するスクリプトを作成しました。
Unix/Linuxのpasteコマンドでも同様の事が可能ですが、大きな違いとして、file1, file2, file3, ... で
最初の1列目が共通な場合、file2以降では共通列を除いて結合していきます。

使用例

./concat_csv.awk -v com_column=1 file1 [file2] ...

com_column: 共通列の数 (file1, file2... の第1列が共通の場合、com_column=1と設定します)

スクリプト

concat_csv.awk

#!/usr/bin/awk -f

BEGIN{
    FS ="," 
    if(com_column == "" ){
        com_column = 5
    }
    for(i=1; i<ARGC; i++){
        file_index[ARGV[i]] = i
    }
}
{
    for(i=1; i<=NF; i++){
        arr[ file_index[FILENAME] , FNR , i ] =$i
        # printf("debug file=%s:arr[%d, %d, %d] = %s\n", FILENAME, file_index[FILENAME], FNR, i, $i)
    }
    file_nf[FILENAME] = NF
}
END{
    # printf("debug com_column=%d\n", com_column)
    for(i=1; i<=FNR; i++){
        for(j=1; j<=ARGC; j++){
            if(j==1){
                for(k=1; k<=file_nf[ ARGV[j] ];k++ ){
                    printf(arr[ file_index[ARGV[j]] , i , k])
                }
            }
            else{
                for(k=com_column+1; k<=file_nf[ ARGV[j] ];k++ ){
                    printf(arr[ file_index[ARGV[j]] , i , k])
                }
            }
        }
        printf("\n")
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0