段落の間に空白行があり、76文字で囲まれた段落を含むテキストファイルがあります。 sedを使用して、これを段落ごとに1行あり、空行がないファイルに変換したいと思います。
入力例:
Start of p1
continued p1
end of p1.
Start of p2
end of p2.
Start of p3
continued p3
even more p3
end of p3.
出力例:
Start of p1 continued p1 end of p1.
Start of p2 end of p2.
Start of p3 continued p3 even more p3 end of p3.
ベストアンサー1
GNU sedの使用
$ sed ':a;N;$!{/\n$/!ba}; s/[[:blank:]]*\n[[:blank:]]*/ /g' textfile
Start of p1 continued p1 end of p1.
Start of p2 end of p2.
Start of p3 continued p3 even more p3 end of p3.
どのように動作しますか?
:a
これはラベルを定義します。
a
N
その後、次の行を読み、改行文字とともに現在の行に追加します。
$!{/\n$/!ba}
(a) ファイルの末尾にない場合そして(b)現在行が空でない場合は、ラベルにジャンプ(分岐)します。
a
s/[[:blank:]]*\n[[:blank:]]*/ /g'
ここに来ると、パターン空間に完全な段落があります。すべての改行(オプションでスペースの前後にスペース)を見つけてスペースに置き換えます。
BSD/OSX sedの使用
試してみてください(テストされていません):
sed -e :a -e 'N;$!{/\n$/!ba' -e '}' -e 's/[[:blank:]]*\n[[:blank:]]*/ /g' textfile
awkを使う
$ awk '{printf "%s ",$0} /^$/{print ""} END{print ""}' text
Start of p1 continued p1 end of p1.
Start of p2 end of p2.
Start of p3 continued p3 even more p3 end of p3.