7.1 行の結合
この節では、N、D、Pコマンドで複数行を処理し、bとtコマンドで分岐します。複数行を扱う手法:D,G,H,N,Pによる複数行の処理と分岐とフロー制御を参照してください。
特定の行を結合します(たとえば、2行目と3行目を結合する場合)。
$ cat lines.txt
hello
hel
lo
hello
$ sed '2{N;s/\n//;}' lines.txt
hello
hello
hello
バックスラッシュで継続されている行を結合します。
$ cat 1.txt
this \
is \
a \
long \
line
and another \
line
$ sed -e ':x /\\$/ { N; s/\\\n//g ; bx }' 1.txt
this is a long line
and another line
#TODO: The above requires gnu sed.
# non-gnu seds need newlines after ':' and 'b'
コード内の説明(日本語訳)
TODO: 上の例にはGNU sedが必要です。GNU以外のsedでは、コマンド「:」と「b」の後に改行が必要です。
空白で始まる行を結合します(たとえば、SMTPヘッダー)。
$ cat 2.txt
Subject: Hello
World
Content-Type: multipart/alternative;
boundary=94eb2c190cc6370f06054535da6a
Date: Tue, 3 Jan 2017 19:41:16 +0000 (GMT)
Authentication-Results: mx.gnu.org;
dkim=pass [email protected];
spf=pass
Message-ID: <[email protected]>
From: John Doe <[email protected]>
To: Jane Smith <[email protected]>
$ sed -E ':a ; $!N ; s/\n\s+/ / ; ta ; P ; D' 2.txt
Subject: Hello World
Content-Type: multipart/alternative; boundary=94eb2c190cc6370f06054535da6a
Date: Tue, 3 Jan 2017 19:41:16 +0000 (GMT)
Authentication-Results: mx.gnu.org; dkim=pass [email protected]; spf=pass
Message-ID: <[email protected]>
From: John Doe <[email protected]>
To: Jane Smith <[email protected]>
# A portable (non-gnu) variation:
# sed -e :a -e '$!N;s/\n */ /;ta' -e 'P;D'
コード内の説明(日本語訳)
移植性のある、GNU以外のsed向けの別の書き方を末尾に示しています。