manpagez: man pages & more
info sed
Home | html | info | man

File: sed.info,  Node: Line length adjustment,  Next: Adding a header to multiple files,  Prev: Text search across multiple lines,  Up: Examples

7.8 Line length adjustment
==========================

This section uses ‘N’ and ‘P’ commands to read and write lines, and the
‘b’ command for branching.  *Note Multiline techniques:: and *note
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

     # Append 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,

© manpagez.com 2000-2026
Individual documents may contain additional copyright information.