start page | rating of books | rating of authors | reviews | copyrights

Unix Power ToolsUnix Power ToolsSearch this book

21.8. Centering Lines in a File

Here's an awk script, written by Greg Ubben, that centers text across an 80-character line. If your system understands #! (Section 36.3), this script will be passed directly to awk without a shell. Otherwise, put this into a Bourne shell wrapper (Section 35.19).

Figure Go to http://examples.oreilly.com/upt3 for more information on: center

#!/usr/bin/awk -f
{
    printf "%" int(40+length($0)/2) "s\n", $0
}

For each input line, the script builds a printf command with a width specification just wide enough to center the line (which awk holds in $0). For instance, a line 60 characters wide would give a value of int(40+60/2), which is 70. That makes the following printf command:

printf %70s\n, $0

Because %s prints a string right-justified, that command gives a 10-character indentation (70 minus 60) on an 80-character line. The right end of the line is also 10 characters (80 minus 70) from the right edge of the screen.

In vi, you can use a filter-through (Section 17.18) command to center lines while you're editing. Or just use center from the command line. For example:

% center afile > afile.centered
% sort party_list | center | lp

-- JP



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.