行の次の部分を3列ファイルの現在の行にマージします。

行の次の部分を3列ファイルの現在の行にマージします。

word @@@ type @@@ sentence各行に書式設定され、「単語」に基づいて昇順にソートされたテキストファイルがあります。ただし、一部の行は一意ではなく、前の行と同じ単語で始まります。つまり、以下のword1を参照してください。

...
word0 @@@ type2 @@@ sentence0
word1 @@@ type1 @@@ sentence1
word1 @@@ type1 @@@ sentence2
word1 @@@ type1 @@@ sentence3
word1 @@@ type2 @@@ sentence4
word2 @@@ type1 @@@ sentence5
...

文を追加して同じ単語と型の組み合わせを持つ行を1行に結合したいので、ファイルの結果は次のようになります。

...
word0 @@@ type2 @@@ sentence0
word1 @@@ type1 @@@ sentence1 ;;; sentence2 ;;; sentence3
word1 @@@ type2 @@@ sentence4
word2 @@@ type1 @@@ sentence5
...

単語と型のフィールドにはスペースはありません。

答え1

wordtype公開した例の入力に示すように、入力がフィールドに対してソートされているとします。

$ cat tst.awk
BEGIN { FS=" @@@ "; ORS="" }
{ curr = $1 FS $2 }
curr != prev {
    printf "%s%s", ORS, $0
    prev = curr
    ORS = RS
    next
}
{ printf " ;;; %s", $NF }
END { print "" }

$ awk -f tst.awk file
word0 @@@ type2 @@@ sentence0
word1 @@@ type1 @@@ sentence1 ;;; sentence2 ;;; sentence3
word1 @@@ type2 @@@ sentence4
word2 @@@ type1 @@@ sentence5

上記のコードは、awkを使用するすべてのUNIXシステムのすべてのシェルで動作し、一度に1行だけメモリに保存し、入力と同じ順序で出力を生成します。

答え2

これはawkの方法です。

$ awk -F'@@@' '{ $1 in a ? a[$1][$2]=a[$1][$2]" ;;; "$3 : a[$1][$2]=$3}END{for(word in a){for (type in a[word]){print word,FS,type,FS,a[word][type]} }}' file 
word0  @@@  type2  @@@  sentence0
word1  @@@  type1  @@@  sentence1 ;;;  sentence2 ;;;  sentence3
word1  @@@  type2  @@@  ;;;  sentence4
word2  @@@  type1  @@@  sentence5

または、より明確に言えば、

awk -F'@@@' '{ 
                if($1 in a){ 
                    a[$1][$2]=a[$1][$2]" ;;; "$3
                }
                else{
                    a[$1][$2]=$3
                }
             }
             END{
                 for(word in a){
                     for (type in a[word]){
                         print word,FS,type,FS,a[word][type]
                     }
                 }
             }' file 

これには、awkLinuxシステムの基本実装であるGNU awk()などの多次元配列を理解する実装が必要ですgawkawk

関連情報