ファイルをマージし、IDフィールドに基づいて列値を取得します。

ファイルをマージし、IDフィールドに基づいて列値を取得します。
bash-3.2$ cat sample.log sample.log.1 sample.log.2
ID COL1 COL2 COL4
1  col1 col2 col4
2  c1   c2   c4
3  co1  co2  co4

ID COL3 COL1
1  col3 col1
2  c3   c1
3  co3  co1

ID COL1 COL2 COL3
1  col1 col2 col3
2  c1  c2   c3
3  co1  co2  co3

データベース内の複数のテーブルに対する選択クエリなど、特定のIDの列値を提供するようにawkスクリプトを作成する必要があります。

ID 1のcol1 col2フィールドとcol3フィールドを指定した場合は、重複した結果があってはなりません。結果は、次のようにする必要があることを意味します。

The result should be
ID COL1 COL2 COL3
1  col1 col2 col3

しかし、

The result should be
ID COL1 COL2 COL3 COL3
1  col1 col2 col3 col3

提案でもいいです。

awk ' BEGIN { while ( (getline line < "sample.log") > 0 ) {ids[substr(line,1,index(line," ")-1)];} } { // get the column values here based on the stored id's .. } ' sample.log sample.log.1 sample.log.2

上記のようなことをしようとしています。これが良い考えなのかよくわかりません。

ベストアンサー1

次のjoinコマンドを使用してこれを実行できます。

join -1 1 -2 1 sample.log sample.log.1 -o 1.1,1.2,1.3,2.2

出力は「単一スペース」で区切られますが、awk を使用して列ソートで書式を再指定できます。

join入力ファイルはソートする必要があります。

おすすめ記事