7.8 Line length adjustment

This section uses N and D commands to search for consecutive words spanning multiple lines, and the b command for branching. See Multiline techniques and Branching and flow control.

This (somewhat contrived) example deal with formatting and wrapping lines of text of the following input file:

$ cat two-cities-mix.txt
It was the best of times, it was
the worst of times, it
was the age of
wisdom,
it
was
the age
of foolishness,

The following sed program wraps lines at 40 characters:

$ cat wrap40.sed
# outer loop
:x

# Appead a newline followed by the next input line to the pattern buffer
N

# Remove all newlines from the pattern buffer
s/\n/ /g


# Inner loop
:y

# Add a newline after the first 40 characters
s/(.{40,40})/\1\n/

# If there is a newline in the pattern buffer
# (i.e. the previous substitution added a newline)
/\n/ {
    # There are newlines in the pattern buffer -
    # print the content until the first newline.
    P

   # Remove the printed characters and the first newline
   s/.*\n//

   # branch to label 'y' - repeat inner loop
   by
 }

# No newlines in the pattern buffer - Branch to label 'x' (outer loop)
# and read the next input line
bx

The wrapped output:

$ sed -E -f wrap40.sed two-cities-mix.txt
It was the best of times, it was the wor
st of times, it was the age of wisdom, i
t was the age of foolishness,