列1に基づいて複数の行を連結します。

列1に基づいて複数の行を連結します。

以下のファイルがあります。

abc, 12345
def, text and nos    
ghi, something else   
jkl, words and numbers

abc, 56345   
def, text and nos   
ghi, something else 
jkl, words and numbers

abc, 15475  
def, text and nos 
ghi, something else
jkl, words and numbers

abc, 123345
def, text and nos
ghi, something else  
jkl, words and numbers

次に変換(結合)したいと思います。

abc, 12345, 56345, 15475, 123345
def, text and nos, text and nos,text and nos,text and nos
ghi, something else, something else, something else, something else   
jkl, words and numbers, words and numbers, words and numbers, words and numbers

ベストアンサー1

出力順序が気に入らない場合は、次のようにします。

$ awk -F',' 'NF>1{a[$1] = a[$1]","$2};END{for(i in a)print i""a[i]}' file 
jkl, words and numbers, words and numbers, words and numbers, words and numbers
abc, 12345, 56345, 15475, 123345
ghi, something else, something else, something else, something else
def, text and nos, text and nos, text and nos, text and nos

説明する

  • NF>1つまり、空でない行だけを処理するだけです。
  • すべての最初のフィールドを連想配列に保存しますa。キーは最初のフィールドで、値は2番目のフィールド(または行の残りの部分)です。キーにすでに値がある場合は、2つの値を連結します。
  • ENDブロック内で連想配列を繰り返して、aすべてのキーとその値を印刷します。

または、次のperl順序を維持します。

$perl -F',' -anle 'next if /^$/;$h{$F[0]} = $h{$F[0]}.", ".$F[1];
    END{print $_,$h{$_},"\n" for sort keys %h}' file
abc, 12345, 56345, 15475, 123345

def, text and nos, text and nos, text and nos, text and nos

ghi, something else, something else, something else, something else

jkl, words and numbers, words and numbers, words and numbers, words and numbers

おすすめ記事