sed: Line length adjustment
1
1 7.8 Line length adjustment
1 ==========================
1
1 This section uses 'N' and 'D' commands to search for consecutive words
11 spanning multiple lines, and the 'b' command for branching. ⇒
Multiline techniques and ⇒Branching and flow control.
1
1 This (somewhat contrived) example deal with formatting and wrapping
1 lines of text of the following input file:
1
1 $ cat two-cities-mix.txt
1 It was the best of times, it was
1 the worst of times, it
1 was the age of
1 wisdom,
1 it
1 was
1 the age
1 of foolishness,
1
1 The following sed program wraps lines at 40 characters:
1 $ cat wrap40.sed
1 # outer loop
1 :x
1
1 # Appead a newline followed by the next input line to the pattern buffer
1 N
1
1 # Remove all newlines from the pattern buffer
1 s/\n/ /g
1
1
1 # Inner loop
1 :y
1
1 # Add a newline after the first 40 characters
1 s/(.{40,40})/\1\n/
1
1 # If there is a newline in the pattern buffer
1 # (i.e. the previous substitution added a newline)
1 /\n/ {
1 # There are newlines in the pattern buffer -
1 # print the content until the first newline.
1 P
1
1 # Remove the printed characters and the first newline
1 s/.*\n//
1
1 # branch to label 'y' - repeat inner loop
1 by
1 }
1
1 # No newlines in the pattern buffer - Branch to label 'x' (outer loop)
1 # and read the next input line
1 bx
1
1 The wrapped output:
1 $ sed -E -f wrap40.sed two-cities-mix.txt
1 It was the best of times, it was the wor
1 st of times, it was the age of wisdom, i
1 t was the age of foolishness,
1