sed: Joining lines
1
1 7.1 Joining lines
1 =================
1
1 This section uses 'N', 'D' and 'P' commands to process multiple lines,
11 and the 'b' and 't' commands for branching. ⇒Multiline
techniques and ⇒Branching and flow control.
1
1 Join specific lines (e.g. if lines 2 and 3 need to be joined):
1
1 $ cat lines.txt
1 hello
1 hel
1 lo
1 hello
1
1 $ sed '2{N;s/\n//;}' lines.txt
1 hello
1 hello
1 hello
1
1 Join backslash-continued lines:
1
1 $ cat 1.txt
1 this \
1 is \
1 a \
1 long \
1 line
1 and another \
1 line
1
1 $ sed -e ':x /\\$/ { N; s/\\\n//g ; bx }' 1.txt
1 this is a long line
1 and another line
1
1
1 #TODO: The above requires gnu sed.
1 # non-gnu seds need newlines after ':' and 'b'
1
1 Join lines that start with whitespace (e.g SMTP headers):
1
1 $ cat 2.txt
1 Subject: Hello
1 World
1 Content-Type: multipart/alternative;
1 boundary=94eb2c190cc6370f06054535da6a
1 Date: Tue, 3 Jan 2017 19:41:16 +0000 (GMT)
1 Authentication-Results: mx.gnu.org;
1 dkim=pass header.i=@gnu.org;
1 spf=pass
1 Message-ID: <abcdef@gnu.org>
1 From: John Doe <jdoe@gnu.org>
1 To: Jane Smith <jsmith@gnu.org>
1
1 $ sed -E ':a ; $!N ; s/\n\s+/ / ; ta ; P ; D' 2.txt
1 Subject: Hello World
1 Content-Type: multipart/alternative; boundary=94eb2c190cc6370f06054535da6a
1 Date: Tue, 3 Jan 2017 19:41:16 +0000 (GMT)
1 Authentication-Results: mx.gnu.org; dkim=pass header.i=@gnu.org; spf=pass
1 Message-ID: <abcdef@gnu.org>
1 From: John Doe <jdoe@gnu.org>
1 To: Jane Smith <jsmith@gnu.org>
1
1 # A portable (non-gnu) variation:
1 # sed -e :a -e '$!N;s/\n */ /;ta' -e 'P;D'
1