重複行をコンマで区切って 1 行にまとめる方法

重複行をコンマで区切って 1 行にまとめる方法

以下のデータがあります:

St1 apt1
St1 apt2
St2 apt5
St3 apt6
St3 apt7
St3 apt8

重複する行を結合し、フィールドをコンマで区切って 2 つの列を作成したいと思います。例:

St1 apt1,apt2
St2 apt5
St3 apt6,apt7,apt8

以下のコマンドを試しましたが、期待どおりに動作しませんでした。

awk 'BEGIN{FS="\t"}; BEGIN{OFS="\t"}; { arr[$1] = arr[$1] $2 }   END {for (i in arr) print i arr[i] }'

結果は次のとおりです。

St1apt1apt2
St2apt5
St3apt6apt7apt8

なにか提案を?

答え1

ほんの少し調整するだけです:

$ awk '
    BEGIN{FS="\t"; OFS=FS}; 
    { arr[$1] = arr[$1] == ""? $2 : arr[$1] "," $2 }   
    END {for (i in arr) print i, arr[i] }
' data
St1    apt1,apt2
St2    apt5
St3    apt6,apt7,apt8

答え2

sed -e '
   :a
   $!N
   s/^\(\(\S\+\)\s\+.*\)\n\2\s\+/\1,/;ta
' yourfile

結果

St1 apt1,apt2
St2 apt5
St3 apt6,apt7,apt8

関連情報