Centering lines (sed, a stream editor)

From Get docs
Sed/docs/latest/Centering-lines


7.2 Centering Lines

This script centers all lines of a file on a 80 columns width. To change that width, the number in \{…\} must be replaced, and the number of added spaces also must be changed.

Note how the buffer commands are used to separate parts in the regular expressions to be matched—this is a common technique.

#!/usr/bin/sed -f
# Put 80 spaces in the buffer
1 {
  x
  s/^$/          /
  s/^.*$/&&&&&&&&/
  x
}

# delete leading and trailing spaces
y/TAB/ /
s/^ *//
s/ *$//

# add a newline and 80 spaces to end of line
G

# keep first 81 chars (80 + a newline)
s/^\(.\{81\}\).*$/\1/

# \2 matches half of the spaces, which are moved to the beginning
s/^\(.*\)\n\(.*\)\2/\2\1/