6.4.2 Branching example: joining lines

As a real-world example of using branching, consider the case of quoted-printable files, typically used to encode email messages. In these files long lines are split and marked with a soft line break consisting of a single ‘=’ character at the end of the line:

$ cat jaques.txt
All the wor=
ld's a stag=
e,
And all the=
 men and wo=
men merely =
players:
They have t=
heir exits =
and their e=
ntrances;
And one man=
 in his tim=
e plays man=
y parts.

The following program uses an address match ‘/=$/’ as a conditional: If the current pattern space ends with a ‘=’, it reads the next input line using N, replaces all ‘=’ characters which are followed by a newline, and unconditionally branches (b) to the beginning of the program without restarting a new cycle. If the pattern space does not ends with ‘=’, the default action is performed: the pattern space is printed and a new cycle is started:

$ sed ':x ; /=$/ { N ; s/=\n//g ; bx }' jaques.txt
All the world's a stage,
And all the men and women merely players:
They have their exits and their entrances;
And one man in his time plays many parts.

Here’s an alternative program with a slightly different approach: On all lines except the last, N appends the line to the pattern space. A substitution command then removes soft line breaks (‘=’ at the end of a line, i.e. followed by a newline) by replacing them with an empty string. If the substitution was successful (meaning the pattern space contained a line which should be joined), the conditional branch command t jumps to the beginning of the program without completing or restarting the cycle. If the substitution failed (meaning there were no soft line breaks), The t command will not branch. Then, P will print the pattern space content until the first newline, and D will delete the pattern space content until the first new line. (To learn more about N, P and D commands see Multiline techniques - using D,G,H,N,P to process multiple lines).

$ sed ':x ; $!N ; s/=\n// ; tx ; P ; D' jaques.txt
All the world's a stage,
And all the men and women merely players:
They have their exits and their entrances;
And one man in his time plays many parts.

For more line-joining examples see Joining lines.