![特定の文字「:」が見つからない場合、どの行を前の行に移動しますか? [コピー]](https://linux33.com/image/140517/%E7%89%B9%E5%AE%9A%E3%81%AE%E6%96%87%E5%AD%97%E3%80%8C%3A%E3%80%8D%E3%81%8C%E8%A6%8B%E3%81%A4%E3%81%8B%E3%82%89%E3%81%AA%E3%81%84%E5%A0%B4%E5%90%88%E3%80%81%E3%81%A9%E3%81%AE%E8%A1%8C%E3%82%92%E5%89%8D%E3%81%AE%E8%A1%8C%E3%81%AB%E7%A7%BB%E5%8B%95%E3%81%97%E3%81%BE%E3%81%99%E3%81%8B%EF%BC%9F%20%5B%E3%82%B3%E3%83%94%E3%83%BC%5D.png)
成績表のテキストファイルがたくさんあります。ある程度まとめられました。最後のクリーニングは次のとおりです。
*.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.