特定の文字「:」が見つからない場合、どの行を前の行に移動しますか? [コピー]

特定の文字「:」が見つからない場合、どの行を前の行に移動しますか? [コピー]

成績表のテキストファイルがたくさんあります。ある程度まとめられました。最後のクリーニングは次のとおりです。

*.txt ファイルにこの内容があります。

Gary: I said something.
Larry: I said something else.
Mr. John: I said this. And maybe this
and I also said this.
Laura: did i say anything.

私はこれが必要です。

Gary: I said something.
Larry: I said something else.
Mr. John: I said this. And maybe this and I also said this.
Laura: did i say anything.

行を移動したい。いいえ前の行にはコロン(:)が含まれています。最後に、各行に改行で終わる文字会話を含めたいと思います。

私はこれを見た質問しかし、どうすればいいのかわかりません。私はsed/awk/python/bash/perlツールなら何でも使うことができます。

答え1

Sedを使用すると、パターンスペースに行を追加し、追加された部分(追加の改行からパターンの終わりまで)にコロン以外の文字のみが含まれていることを確認し、その後、最後の改行を空白に置き換えることができます。

sed -e :a -e '$!N; s/\n\([^:]*\)$/ \1/;ta' -e 'P;D' file.txt
Gary: I said something.
Larry: I said something else.
Mr. John: I said this. And maybe this and I also said this.
Laura: did i say anything.

答え2

どうですかawk?最後の行のコピーを保持します。コロンがない場合(NF == 1)、実際の行を最後の行に追加して2行を同時に印刷します。 $ 0は空の文字列に設定されているため、記憶されません。

awk -F: 'NF == 1 {LAST = LAST " " $0; $0 = ""}; LAST {print LAST}; {LAST = $0} END {print LAST}' file
Gary: I said something.
Larry: I said something else.
Mr. John: I said this. And maybe this and I also said this.
Laura: did i say anything.

答え3

もう一つのawk試み:

BEGIN{RS=":";ORS=":"; # use ":", ie. change of speaker, to recognise end of record
      FS="\n"}        # OFS is still " ", so newlines in input converted to spaces in output
!$NF { ORS="" }       # detect last line (no next speaker) and don't append a :
NF>1 {$NF = "\n" $NF} # restore the newline before the speaker's name
{print}               # print the result

答え4

sed -e '
   /:/{$!N;}
   /\n.*:/!s/\n/ /
   P;D
' file.txt

 Gary: I said something.
 Larry: I said something else.
 Mr. John: I said this. And maybe this and I also said this.
 Laura: did i say anything.

関連情報