Open Source

Format text with pr

Learn to use the Linux <i>pr</i> utility to break up a large file into pages with a header that can be sent to the printer.

This tip is from TechRepublic's free Linux NetNote newsletter. Sign up instantly to begin receiving the Linux NetNote in your inbox.

You can use Linux's pr utility to convert text files into text suitable for printing to a printer. This tool's basic use is to take one large file and break it up into pages, adding a header to each page.

For example, pr would convert a file that contains 150 lines into a file that contains three pages of text that you could then send to the printer.

By default, each page contains 66 lines of text. However, you can change this by using the -l switch with the pr command.

A number of arguments are available to customize the output of the text. By default, the header at the top of each page is the filename.

However, you can customize this. Here's an example:

$ pr -h "My report" file.txt

Rather than using "file.txt" as the header, this formats the file.txt file and uses "My report" as the centered heading on each page.

You can also split a file into columns. This can be especially useful for a file that contains short lines of text; if a file contains long lines of text, pr will truncate the text on each line.

To turn this report into a two-column file, execute the following:

$ pr -2 -h "My report" file.txt

By default, pr pads each page with newline characters (i.e., empty lines). But you can also change this so pr uses a form-feed character instead. To use form-feed characters, execute the following:

$ pr -f file.txt

This is particularly useful if you only want to print the file and aren't concerned about saving it. But if you want to save the file, keeping the newline characters makes it look a little sharper.

Keep in mind that pr prints to standard output, which is useful if you want to redirect it to the lpr tool to immediately print. If you want to keep the resulting output in a file, you need to redirect it. Here's an example:

$ pr file.txt >file.output

There are a number of other options you can use with the pr utility. For more information, check out the utility's man pages.

About Vincent Danen

Vincent Danen works on the Red Hat Security Response Team and lives in Canada. He has been writing about and developing on Linux for over 10 years and is a veteran Mac user.

Editor's Picks